【问题标题】:Embed partial templates with Backbone / Marionette / Underscore templates使用 Backbone / Marionette / Underscore 模板嵌入部分模板
【发布时间】:2014-10-21 16:45:12
【问题描述】:

在带有下划线模板的 Marionette 中,是否可以将一个模板文件“包含”到另一个模板文件中 - 以便可以在多个模板之间共享通用标记?

我们使用 requireJS 在何时加载 .tpl 文件 - 然后将 tpl 文件分配给 Marionette 视图;

  View.MyView = Marionette.ItemView.extend({
        template: 'parent_template.tpl'
  });

其中 'parent_template.tpl' 包含类似的内容。

  <h1>A Parent View</h1>
  <button class='btn-one'>One</button> 
  <button class='btn-two'>Two</button>
  <button class='btn-three'>three</button>

我想做的是将按钮提取到一个普通的 tpl,其他 tpl 可以使用,比如...

其中 'parent_template.tpl' 包含类似的内容。

  <h1>A Parent View</h1>
   {{child_template.tpl}}

而 'child_template.tpl' 包含类似的东西。

  <button class='btn-one'>One</button> 
  <button class='btn-two'>Two</button>
  <button class='btn-three'>three</button>

然后许多其他模板可以拉入共享模板。

有什么想法吗?

【问题讨论】:

  • 我对 Marionette 不熟悉,但 Underscore 模板被设计为超级简单,根本不包含任何逻辑(包括“嵌入”机制)。如果您使用更高级的模板系统,例如 Handlebars,您可以推出自己的包含“帮助程序”或使用像 npmjs.org/package/handlebars-helper-include 这样的预构建系统。

标签: templates backbone.js underscore.js marionette


【解决方案1】:

我解决这个问题的方法是使用 templateHelpers。

像往常一样使用 require JS 加载部分模板。 然后通过templateHelper将子模板的引用传递给父模板;

define(['tpl!parent.tpl', 'tpl!child.tpl'], function (ParentTemplate, ChildTemplate) {

   View.MyView = Marionette.View.extend({
      template: ParentTemplate,
      templateHelpers: function() {
        return {
          childTpl: ChildTemplate
        }
      }
    });
}

父模板通过助手包含子模板

<h1>parent template</h1>
<%= childTpl(obj) %>

如果您传递'obj' - 模板模型,孩子可以访问数据

<h2>this is the child, that can access the parent data <%= title %></h2>

【讨论】:

    【解决方案2】:

    对我来说,在模板中包含模板闻起来很奇怪。 您可以将 Mariontte.LayoutView 与子视图一起使用:

    按钮子视图:

    Buttons = Marionette.ItemView.extend({
             template: 'child_template.tpl'
    });
    

    布局:

    MyView = Marionette.LayoutView.extend({
             template: 'parent_template.tpl',
             region : {
                  buttonRegion : '.myButtonsRegion'
             },
             onShow : function(){
                  var buttons = new Buttons();
                  this.buttonRegion.show(buttons);
             }
    });
    

    然后是 parent_template.tpl :

    <h1>A Parent View</h1>
    <div class="myButtonsRegion"></div>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-04-23
      • 1970-01-01
      • 2013-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多