在Handlebars.template方法中注入预编译的把手模板

时间:2016-10-03 12:31:06

标签: handlebars.js

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

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

 });

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

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

预编译输出如下所示:

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

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

如果是编译模板,则没有问题。

非常感谢提前

1 个答案:

答案 0 :(得分:0)

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

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

将解决问题

相关问题