Mustache - 我怎样才能*一次*为一个迭代做一些事情? [英] Mustache - how can I do something *once* for an iterable?
问题描述
假设我有一个 user
,他有很多 items
Say I have a user
, who has many items
如果items
中有最后一个项目,我怎么能有一个单亲爱的,你有项目!"?
How can I have a single 'Sweet, you have items!', provided there's at last one item in items
?
{{#user.items}}
Sweet, you have items!
{{/user.items}}
注意:我知道我可以为每个项目创建一个重复的部分.但现在我不想那样做.
Note: I know I can create a section that will repeat for each item. But right now I don't want to do that.
推荐答案
答案(就像 Mustache 的大多数东西一样)是在渲染之前准备好你的视图模型":)
The answer (like most things Mustache) is "prepare your view model before rendering" :)
但是如果你不喜欢这个,你通常可以像这样在 Mustache.js 中伪造它:
But if you're not into that, you can usually fake it in Mustache.js like this:
{{# user.items.0 }}
Sweet, you have items!
{{/ user.items.0 }}
(更多的 Mustachey 方法是向用户添加一个 hasItems
属性或函数并使用它)
(The more Mustachey way would be to add a hasItems
property or function to the user and use that instead)
{{# user.items.length }}
做同样的事情,并且不会污染您的上下文堆栈.你应该改用它.
{{# user.items.length }}
does the same thing, and doesn't pollute your context stack quite as much. You should use that instead.
嗯,真的,你应该使用视图模型.但第二好的应该是 user.items.length
.
这篇关于Mustache - 我怎样才能*一次*为一个迭代做一些事情?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!