【问题标题】:Iterate through two objects in Handlebars遍历 Handlebars 中的两个对象
【发布时间】:2015-10-27 18:25:12
【问题描述】:

我有一个主干模型,我正在尝试从中提取特定值。类似的东西:(使用原始对象,但假设它是一个主干模型)

var x = {
    primary : ["a","b","c"],
    attributes : {
        a : 1,
        b : 2,
        d : 4
    }
}

最后应该渲染1 2

我在想类似的事情

{{#each primary}}
    {{#if attributes[this]}}{{attributes[this]}}{{/if}}
{{/each}}

但这似乎不起作用。想法?

【问题讨论】:

  • 在使用 Handlebars 时,通常最好先用纯 JavaScript 进行数据整理和操作,然后再使用模板。重新格式化您的数据,以便您可以在模板内进行简单的迭代。
  • 别忘了有一个方法model.toJSON()来处理这种事情。

标签: backbone.js handlebars.js


【解决方案1】:

lookup为它制作的助手:

查找帮助程序允许使用 Handlebars 变量进行动态参数解析。这对于解析数组索引的值很有用。

var source = $("#template").html(); 
var template = Handlebars.compile(source); 

var data = {
  primary : ["a","b","c"],
  attributes : {
      a : 1,
      b : 2,
      d : 4
  }
};

$('body').append(template(data));
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.0.11/handlebars.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script id="template" type="text/x-handlebars-template">
{{#primary}}
	{{lookup ../attributes this}}
{{/primary}}
</script>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-07-22
    • 2012-09-07
    • 2015-10-15
    • 2015-05-25
    • 2014-05-08
    • 2023-01-10
    • 2018-03-10
    相关资源
    最近更新 更多