Mustache - how can I do something *once* for an iterable?

◇◆丶佛笑我妖孽 提交于 2019-12-02 00:10:40

问题


Say I have a user, who has many 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.


回答1:


The answer (like most things Mustache) is "prepare your view model before rendering" :)

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 }}

(The more Mustachey way would be to add a hasItems property or function to the user and use that instead)

Edit: {{# user.items.length }} does the same thing, and doesn't pollute your context stack quite as much. You should use that instead.

Well, really, you should use a view model. But second best would be user.items.length.



来源:https://stackoverflow.com/questions/19572096/mustache-how-can-i-do-something-once-for-an-iterable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!