使用单个变量来定义mustache标记

时间:2013-06-17 13:13:28

标签: javascript jquery templates mustache

有没有选项用一些定义变量设置mustache标签?像这样:

的Json

{
    "color_set_01": [
        "white", "black"
        ],
    "color_set_02": [
        "green", "red"
    ]
}

的JavaScript

var color = 'color_set_' + options.number;

$.getJSON('json/data.json', function(data) {
    var template = "<ul>{{color}}<li class="{{.}}"></li>{{/color}}</ul>";
    var html = Mustache.to_html(template, data);
    colors_panel.html(html);
});

和期望的结果,如果它是color_set_01 aray

<div class="colors_panel">
    <ul>
      <li class="white">
      <li class="black">
    </ul>
</div>

1 个答案:

答案 0 :(得分:1)

好的,在快速查看http://coenraets.org/blog/2011/12/tutorial-html-templates-with-mustache-js/后,我认为这样可行:

var template = "<ul>{{#"+color+"}}<li class=\"{{.}}\"></li>{{/"+color+"}}</ul>";

似乎#设置了使用列表的能力,.基本上是列表中的每个项目。此外,您需要在模板字符串中转义引号。

这也假设您的JSON应如下所示:

{
    "color_set_01": [
        "white", "black"
    ],
    "color_set_02": [
        "green", "yellow"
    ]
}

如果您的JSON中有color_set个以上的内容,那么您必须向我展示color_set_01的父母的内容,直到最高层为我提供帮助。