【问题标题】:Handlebars template inside HandlebarsHandlebars 内的 Handlebars 模板
【发布时间】:2013-10-23 14:06:45
【问题描述】:

我正在尝试使用 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 模板中,则它不起作用,因为 NodeJS Handlebars 编译器正在解释 {{text}}。

【问题讨论】:

    标签: node.js backbone.js handlebars.js


    【解决方案1】:

    试试:

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

    【讨论】:

      【解决方案2】:

      我已通过使用名为“braces”的助手修复它:

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

      并使用:

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

      有没有什么方法可以在不使用助手的情况下做到这一点?

      【讨论】:

      • vkurchatkin 的解决方案要简单一些 ;)
      • 为我工作过:Node.js 使用 Express.js 使用 express-hbs 包。
      【解决方案3】:

      您可以在app.js 中定义助手

      app.engine( '.hbs', hbs({ extname: '.hbs', defaultLayout: 'base', ... helpers: { default: hbsHelper(), // this is the default helpers if you have like handlerbars-helpers raw() { return 'your templates' } } }) );

      在你的情况下,它是

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

      然后在您的前端文件(例如.hbs)中,只需包含{{{raw}}},您就可以在不渲染的情况下使用您的模板。这样您就可以编写普通模板而无需任何其他修改,因为{{{raw}}} 只会将其呈现为html。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-12-02
        • 1970-01-01
        • 2016-12-17
        • 1970-01-01
        • 1970-01-01
        • 2014-03-11
        • 2015-02-03
        • 2017-12-21
        相关资源
        最近更新 更多