处理 Mustache.js 中的空列表
我正在使用 Mustache.js 在 JavaScript 中渲染模板。我想检查列表是否为空或不隐藏以下示例中的
标记。这是可能的还是 Mustache.js 太缺乏逻辑了?
这是模板:
<h2>Persons:</h2>
<ul>
{{#persons}}
{{name}}
{{/persons}}
</ul>
这是数据:
{
"persons":[
{"name": "max"},
{"name": "tom"}
]
}
I'm using mustache.js to render a template in javascript. I'd like to check if a list is empty or not to hide the <h2>
tag in the following example. Is this possible or is mustache.js too logic-less?
This is the template:
<h2>Persons:</h2>
<ul>
{{#persons}}
{{name}}
{{/persons}}
</ul>
and this is the data:
{
"persons":[
{"name": "max"},
{"name": "tom"}
]
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
为这个问题苦苦挣扎了半天,终于找到了一个简单的解决办法!
不要检查列表,而是检查它的第一项是否不为空!
模板:
数据:
输出:
数据:
输出:
After struggling for half a day with this problem, I've finally found an easy solution!
Don't check for the list, but check if its first item is not empty!
Template:
Data:
Output:
Data:
Output:
您可以使用persons.length。如果它是真值(即大于 0),则将渲染该块。
You could use persons.length. If it is a truthy value (i.e. greater than 0) then the block will be rendered.
为了保持模板无逻辑,您可以在渲染模板之前进行此检查:
然后您的模板将如下所示:
To keep your template logic-less, you can make this check before rendering the template:
Then your template will look like this:
请改用车把。它是 Mustache 的超集,可为您提供所需的更多功能。 Mustache 社区要求提供此功能,但维护者拒绝添加。
Use handlebars instead. It's a superset of Mustache which gives you that little bit more power that you need. The mustache community asked for this feature but the maintainer refuses to put it in.
在 javascript 中,您可以使用
{{#names.length}}{{/names.length}}
或{{#names.0}}
进行检查(如果您是)在 javascript 之外(例如在 pystache 或 Scalate 中),你就不走运了。唯一的解决方案是引入一个单独的布尔值,或者将数组嵌套在一个对象中,如果您有一个空数组,则完全避免使用该对象,就像 maxbeatty 建议的那样。
In javascript you can check with
{{#names.length}}{{/names.length}}
or with{{#names.0}}
If you're outside of javascript (e.g. in pystache or Scalate), you're out of luck. The only solution then is to introduce a separate boolean, or nest your array in an object which you avoid entirely if you have an empty array, like maxbeatty suggested.