【问题标题】:Use single variable to define mustache tag使用单个变量来定义 mustache 标签
【发布时间】:2013-06-17 13:13:28
【问题描述】:

是否有任何选项可以使用一些定义变量来设置 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>

【问题讨论】:

  • 编辑对我来说改变了很多问题,但我仍然不确定你想用color_class得到什么
  • color_class 将是我指定数组中的颜色...这就是我使用列表的原因
  • 但是如果你有一个字符串列表,我猜其中一个是“super_green”?你希望从中得到什么?你能告诉你在调用Mustache.to_html() 之后你期望html 是什么吗?
  • 好的,现在就像我的设置一样

标签: javascript jquery templates mustache


【解决方案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_sets,那么您必须在顶部显示 color_set_01 的父母是什么,以便我进一步提供帮助。

【讨论】:

  • 我认为您没有显示完整的 JSON,是否有比 color_sets 更高的级别?我将更新我的帖子以显示 mustache 的期望。
  • 好的,但是您的 JSON 将每个 color_set 作为单独的对象。你需要重新格式化,就像我的帖子一样。
  • 现在如果我在 mustache tamplate 中设置内联 (&lt;ul&gt;{{#color_set_01}}&lt;li class=\"{{.}}\"&gt;&lt;/li&gt;{{/color_set_01}}&lt;/ul&gt;) 我有成功的结果但是如果我使用我的变量我有空列表:(
  • 好的,它工作得很好,我爱你 :),非常感谢你的耐心和帮助,BR 和 +1 给你
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多