【问题标题】:Backbone: mixing html and javascript in templateBackbone:在模板中混合 html 和 javascript
【发布时间】:2012-09-20 10:32:46
【问题描述】:

在这个 Backbone 应用程序 http://arturadib.com/hello-backbonejs/docs/5.html 的“hello world”示例中,作者像这样内联呈现模板

render: function(){
      $(this.el).html('<span style="color:black;">'+this.model.get('part1')+' '+this.model.get('part2')+'</span> &nbsp; &nbsp; <span class="swap" style="font-family:sans-serif; color:blue; cursor:pointer;">[swap]</span> <span class="delete" style="cursor:pointer; color:red; font-family:sans-serif;">[delete]</span>');
      return this; // for chainable calls, like .render().el
    },

虽然功能强大,但有点难以管理的 html 连接。

我见过其他 Backbone 应用程序的作者使用下划线的模板功能在视图中设置模板

template: _.template($('#my-template').html()),

然后渲染它而不是html

$(this.el).html(this.template(this.model.toJSON()));

我想在 hello world 应用程序中尝试这种技术,但是当我创建模板文件时,我遇到了它不是严格意义上的 html 的问题。你会注意到它调用函数

 this.model.get('part2')

我用作模型的模板(来自另一位作者的应用程序,见下文)仅包含 html。

问题,我需要做什么才能在同一个模板文件中包含 javascript 和 html 以便调用模型?

<script type="text/template" id="item-template">
      <div class="company">
        <div class="display">
          <span class="company-text"></span>
          <span class="company-mood">
            <span class="mood"></span>
          </span>
          <span class="company-destroy"></span>
        </div>
        <div class="edit">
          <input class="company-input" type="text" value="" />
        </div>
      </div>
    </script>

【问题讨论】:

  • 你是说这些? &lt;% // arbitrary javascript here %&gt;
  • @orangewarp 在 OP 中显示的示例模板中,我可以在 中包含任意 javascript 吗?这是开箱即用的骨干吗?
  • 它是 Underscore 的一部分,是 Backbone 的依赖项,所以如果你使用 Backbone,你可以很好地使用 Underscore 的模板系统。哎呀, _.template() 函数是一个下划线函数。 :-) 我在答案中包含了一个链接,可以帮助您弄清楚它是如何工作的。

标签: backbone.js


【解决方案1】:

请参阅此链接Underscore Template,了解您想要完成的任务的详细信息。

但总的来说,如果您只是想插入您的 this.model.get('someAttr');,您需要做的就是将其包含在您的模板中。

// Since you call it like this:
$(this.el).html(this.template(this.model.toJSON()));

// Just include this
<div>
    <%= someAttr %>
</div>

您基本上是传入模型属性对象,而下划线模板只是插入该对象的属性。你可以传入任何你想要的东西,尽管你对渲染调用所做的可能是最常见的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-04-30
    • 2017-02-15
    • 2014-08-04
    • 2021-12-24
    • 2023-04-01
    • 2019-12-15
    • 2011-12-19
    相关资源
    最近更新 更多