Backbone.js 主干:在模板中混合html和javascript

Backbone.js 主干:在模板中混合html和javascript,backbone.js,Backbone.js,在这个主干应用程序的“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:s

在这个主干应用程序的“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

$(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>

查看此链接以了解有关您想要完成的任务的详细信息

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

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

// Just include this
<div>
    <%= someAttr %>
</div>
//既然您这样称呼它:
$(this.el).html(this.template(this.model.toJSON());
//包括这个

基本上是传入模型属性对象,下划线模板只是插入该对象的属性。您可以传入任何您想要的内容,尽管您对render调用所做的操作可能是最常见的。

您是指这些吗
@orangewarp在OP中显示的示例模板中,我可以在其中包含任意javascript吗?它是下划线的一部分,是backbone所具有的依赖性,所以如果您使用backbone,您会很好地使用下划线的模板系统。见鬼,uz.template()函数是一个下划线函数。:-)我在答案中包含了一个链接,可以帮助您了解它是如何工作的。
// Since you call it like this:
$(this.el).html(this.template(this.model.toJSON()));

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