Search code examples
htmlmustachemustache.php

Is there a way in mustache to render a block if a section is present without iterating?


I have a section with a header that I want to show only if the array is populated, something like this:

<h1> These are the elements in the array </h1>
<ul>
    {{#myArray}}
    <li>{{name}} - {{value}}</li>
    {{/myArray}}
</ul>

How can I render the <h1> only if myArray is populated?

If i put it inside the # section it is rendered once for every element in the array, which is not what i want.

What's the correct way to do this?


Solution

  • {{#myArray.length}}
         <h1> These are the elements in the array </h1>
    {{/myArray.length}}
    

    The .length will return 0 for empty arrays so we have achieved a real falsey value.

    DEMO

    In terms of PHP:

    {{#myArray.0}}
         <h1> These are the elements in the array </h1>
    {{/myArray.0}}