mustache.js是否支持这样的表达式? - > {{type ==“a”}}
我该怎么做?
髭:
{{#items}}
{{type == "a"}}
<li>{{name}} {{type}}</li>
{{/link}}
{{type == "b"}}
<strong>{{name}} {{type}}</strong>
{{type == "c"}}
<span>{{name}} {{type}}</span>
{{/link}}
{{/items}}
JSON:
{
"header": "Colors",
"items": [
{"name": "red", "type": "a", "url": "#Red"},
{"name": "green", "type": "b", "url": "#Green"},
{"name": "blue", "type": "c", "url": "#Blue"}
],
"empty": false
}
想要输出:
<li>red a</li>
<strong>green b</strong>
<span>blue c</span>
答案 0 :(得分:0)
你不能因为Mustache没有逻辑。
最佳做法是更改输入JSON,使输入中已包含“逻辑”。类似的东西:
{
"header": "Colors",
"items": [
{"a": {"name": "red", "url": "#Red"}},
{"b": {"name": "green", "url": "#Green"}},
{"c": {"name": "blue", "url": "#Blue"}}
],
"empty": false
}
然后:
{{#items}}
{{#a}}
<li>{{name}} {{type}}</li>
{{/a}}
{{#b}}
<strong>{{name}} {{type}}</strong>
{{/b}}
{{#c}}
<span>{{name}} {{type}}</span>
{{/c}}
{{/items}}
会产生你想要的东西。
修改强> 不知怎的,我无法让上面的例子工作。我正在使用Hogan(由Twitter维护的胡子版本,速度更快,还有一些额外的东西,你可以用它做,一定要检查出来)但我很确定没有任何东西与上述东西应该正常工作的事实有关。
无论如何,我可以在提供的演示页面上进行以下工作,该演示页面与原始示例保持一致,并完成您想要的输出。一般说明:您可以检查字段是否存在(例如使用{{#isa}}
),但标签中不能包含任何其他逻辑。
{{#items}}
{{#isa}}
<li><strong>{{name}}</strong></li>
{{/isa}}
{{#isb}}
<li><a href="{{url}}">{{name}}</a></li>
{{/isb}}
{{#isc}}
<li><span href="{{url}}">{{name}}</span ></li>
{{/isc}}
{{/items}}
JSON
{
"header": "Colors",
"items": [
{"name": "red", "isa": true, "url": "#Red"},
{"name": "green", "isb": true, "url": "#Green"},
{"name": "blue", "isc": true, "url": "#Blue"}
],
"empty": false
}
HTH