【问题标题】:Pass variables to handlebars helper call将变量传递给车把助手调用
【发布时间】:2013-08-12 20:07:40
【问题描述】:

我想将模板数据传递给我定义的“文本字段”辅助方法,如下所示:

{{textfield label="{{label}}"
            id="account_{{attributes.id}}"
            name="account[{{attributes.name}}]"
            class="some-class"
            required="true"}}

(注意 {{textfield}} 助手调用中的 {{label}} 和 {{attributes.id}} 引用)

这里是我设置模板的地方:

data = {
  "attributes": {
    "id": "name",
    "name": "name"
  },
  "label": "Name"
}
var templateHtml = 'markup here';
var template = Handlebars.compile(templateHtml);
var formHtml = template(data);

这是jsFiddle

当我运行它时,我仍然在编译的标记中看到 {{placeholders}}。

我怎样才能做到这一点?

【问题讨论】:

    标签: javascript templating handlebars.js


    【解决方案1】:

    您使用不正确的语法将命名参数传递给您的车把助手。你想要的是这样的:

    var data = {
      "attributes": {
        "name": "name"
      }
    }
    var templateHtml = '{{textfield name=attributes.name}}';
    var template = Handlebars.compile(templateHtml);
    var formHtml = template(data);
    

    还有一个更新的小提琴:http://jsfiddle.net/3yWn9/1/

    【讨论】:

    • 太棒了!正是我正在寻找的答案。谢谢!所以关键是 1) 在帮助调用中不包括变量名周围的大括号和 2) 不包括变量名周围的引号。
    • 问题:如果我想这样做: id=account_attributes.id 怎么办?在这种情况下,attributes.id 似乎没有正确解析,并且根据浏览器调试器,id 设置为''。此外, id=account[attributes.name] 会导致语法错误。关于解决方法的任何想法?
    • 据我所知,这是 Handlebars 的一个限制。您可能希望预先组装 id 并将其与数据一起传递,或者在您的帮助程序中进行连接。
    【解决方案2】:

    好吧,看来编译模板两次是可行的。从效率的角度来看很糟糕,但事实就是如此。如果有人有其他解决方案,请发帖。

    var data = { "something": "value", "id": "theId", "theClass": "class-here", "value": "the value" };
    var markup = $('#test-template').html();
    var template = Handlebars.compile(markup);
    var compiled = template(data);
    var template2 = Handlebars.compile(compiled);
    var compiled2 = template2(data);
    $('body').append(compiled2);
    

    这是一个新的jsFiddle 演示双重编译。

    【讨论】:

    • 这是有效的,因为您的第一次编译的输出包含来自您的助手的占位符。
    猜你喜欢
    • 2014-09-25
    • 2013-08-14
    • 2013-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-20
    • 2016-01-07
    • 2014-06-24
    相关资源
    最近更新 更多