【问题标题】:Injecting precompiled handlebars template in Handlebars.template method在 Handlebars.template 方法中注入预编译的车把模板
【发布时间】:2016-10-03 12:31:06
【问题描述】:

您好,我目前正在使用 Express Handlebars 设置 [https://github.com/ericf/express-handlebars][1] 来呈现已编译和预编译的模板。在预编译的情况下,我已经配置了 express 中间件以将车把模板作为预编译并手动配置注册车把预编译模板,如下所示:

hbs.getTemplates('views/partials/page/', {
                    cache      : app.enabled('view cache'),
                    precompiled: true
                }).then(function (templates) {

           var templatesArr = hbs.handlebars.templates = hbs.handlebars.templates || {}

         // extract all templates names and values
        templates = Object.keys(hbs.handlebars.templates).map(function (name) {

                  //get precompiled template data
                  var templateSpec = templates[name]

                 //Inject precompiled data into Handlebars.template method
                 var precompileTemplateRef = hbs.handlebars.template(templateSpec)

                //templateSpec is treated as String rather than Object 
                //and this is where the things break because 
                //handlebars.template expects Object

                //Register precompileTemplateRef with Handlebars so that 
                //precompiled template can be extracted for later use by using 
                //template name

                templatesArr[name] = precompileTemplateRef

 });

当我运行 express 服务器时,hbs.handlebars.template 不会被执行,因为上面提到的 templateSpec 是作为字符串而不是对象接收的。

即使使用 JSON.parse(templateSpec) 也不起作用,因为预编译的输出不是 JSON,而是 Object 文字。

预编译的输出如下所示:

{"1":function(container,depth0,helpers,partials,data) {var helper;ret.......

我想知道是否可以在运行时将预编译的输出注入 Handlebars.template(templateSpec) 或者我是否必须在已注册 Handlebars.templates 的文件系统中创建预编译模板。

在编译模板的情况下没有问题。

非常感谢提前

【问题讨论】:

    标签: handlebars.js


    【解决方案1】:

    根据以下链接,这是 Handlebars 的一个未解决问题: https://github.com/wycats/handlebars.js/issues/922 https://github.com/wycats/handlebars.js/issues/1033

    var templateSpec = (new Function('return ' + templates[name])());
    

    解决问题

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-03
      • 1970-01-01
      相关资源
      最近更新 更多