Search code examples
templatingmustache

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


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.


Solution

  • 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.