繁体   English   中英

将变量从骨干视图发送到Jade模板

[英]Send variable from backbone view to jade template

我的index.jade中有以下模板:

....
<script type="text/template" id="sample-template">
  a(href="<%= link.href %>") <%= link.title %>
</script>
....

我在主干视图中有以下代码,该代码将一个名为link的变量发送到index.jade。

....
var SampleView = Backbone.View.extend({
  template: _.template($('#sample-template').html()),

  render: function() {
    this.$el.append(this.template({
      link: this.model.toJSON()
    }));
    return this;
  }
});
....

现在,当我渲染该模板时,将得到以下输出:

<a href="<%= link.href %>"> sample link

您看,我得到了title变量的正确输出。 但是问题出在href 它不会显示link.href的值。

最终,我发现了问题所在。 因为jade是可与node一起使用的模板引擎(实际上是在服务器端),所以它在客户端使用方面缺乏支持。 因此,当您使用下划线_.template函数编译一个jade模板时,就不能指望有一个功能模板文件。 但是,还有一种将变量从主视图发送到Jade模板的替代方法。 您可以创建一个助手功能,该功能可以打印您想要的翡翠模板中的任何内容。

....
var SampleView = Backbone.View.extend({
  template: _.template($('#sample-template').html()),

  render: function() {
    this.$el.append(this.template({
      link: this.model.toJSON(),
      ahref: this.ahref
  }));
  return this;
  },

  ahref: function( href, title ) {
    return '<a href=' + href + '>' + title + '</a>';
  }

});
....

然后,我需要将link帮助器函数传递给jade模板。

....
<script type="text/template" id="sample-template">
  ahref(link.href, link.title);
</script>
....

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM