【问题标题】:Send variable from backbone view to jade template将变量从主干视图发送到玉模板
【发布时间】:2015-03-06 18:09:20
【问题描述】:

我的 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 的值。

【问题讨论】:

  • 您是否尝试过从 href 赋值中删除双引号?请参阅this 答案。
  • @pdoherty926 是的,我删除了双引号,但出现以下错误:unexpected token &lt;

标签: javascript node.js backbone.js pug


【解决方案1】:

最后我发现了它的问题所在。因为jade 是一个与node 一起工作的模板引擎(实际上是在服务器端),所以它在客户端使用方面缺乏支持。所以当你编译一个带有下划线_.template 函数的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辅助函数传递到玉模板中。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-05-16
    • 1970-01-01
    • 1970-01-01
    • 2012-10-07
    • 2013-01-21
    • 2015-08-24
    • 1970-01-01
    相关资源
    最近更新 更多