Handlebars模板内部嵌套Handlebars

3

我正在尝试使用NodeJS和Backbone渲染Handlebars模板。

到目前为止,在HTML文件中,我的工作完美无误:

app.MyView = Backbone.View.extend({
 ...    
 render: function() {           
   var template = Handlebars.compile( $("#my-template").html());        
   this.$el.html( template(this.model.toJSON()) );
   return this;
 }
 ...
});

查看HTML内部:

<script type="text/x-handlebars-template" id="my-template">
   {{text}}
</script>

然而,如果我将这个视图放在Handlebars模板中,它就不能正常工作,因为{{text}}被NodeJS Handlebars编译器解释了。
3个回答

5

尝试:

<script type="text/x-handlebars-template" id="my-template">
   \{{text}}
</script>

0

我通过使用一个名为“braces”的辅助工具来解决了这个问题:

...
exports.braces = function(obj1){
   return '{{'+param+'}}';
}
...

并使用:

<script type="text/x-handlebars-template" id="my-template">
   {{{braces 'text'}}}
</script>

有没有不使用辅助程序来完成这个的方法?


vkurchatkin的解决方案稍微简单一些 ;) - Alexander Rechsteiner
我使用Node.js和Express.js,以及express-hbs包,这对我很有效。 - Alexander Rechsteiner

0

你可以在 app.js 中定义帮助函数,如下所示:

app.engine( '.hbs', hbs({ extname: '.hbs', defaultLayout: 'base', ... helpers: { default: hbsHelper(), // 如果像处理bars-helpers一样,则为默认帮助函数 raw() { return '你的模板' } } }) );

对于你的情况,它是这样的:

raw() { return '<script type="text/x-handlebars-template" id="my-template"> {{text}} </script>' } 在你的代码中用 ` 替换 '。

然后在你的前端文件中(例如 .hbs),只需包含 {{{raw}}},你就可以在不渲染的情况下使用你的模板了。因此,你可以编写正常的模板而无需进行任何其他修改,因为 {{{raw}}} 会将其呈现为 HTML。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接