3

I would like to be able to check if a list is empty, and if it's not print a block, but I don't want to repeat that block for each item. I just want to be able to echo it once.

Give this following structure:

array(
    "teasers" => array(
        array("title"=>"Teaser Title 1"),
        array("title"=>"Teaser Title 2")
    )
);


{{# teasers }}

    <div class="items-wrap">

        <div class="items">

            {{# . }}

                <div class="item">

                    {{ title }}

                </div>

            {{/ . }}

           </div>

    </div>

{{/ teasers }}

I would like the items-wrap div to only print once, and repeat the item div for each item in the array. As is right now, the items-wrap is repeating once for each item in the teasers array. So... is there a way to check if the main array is not empty, but not repeat it?

The goal is to only print the items-wrap once, if needed.

gdaniel
  • 1,307
  • 2
  • 10
  • 17

3 Answers3

4

Yes, there's a way. Mustache has the method length. If equal ZERO, is false and the block will not be rendered. Your example:

{{# teasers.length }}
<div class="items-wrap">
    <div class="items">
        {{# teasers }}
            <div class="item">
                {{ title }}
            </div>
        {{/ teasers }}
    </div>
</div>
{{/ teasers.length }}

The tag {{teasers.length}} will check the number of items inside {{teasers}} and will render the block only if not empty.

More information here.

This answer is too late, but I hope it helps someone.

Maak
  • 4,720
  • 3
  • 28
  • 39
Diego Somar
  • 941
  • 1
  • 11
  • 28
1

In terms of PHP:

{{#myArray.0}}...{{/myArray.0}}

https://stackoverflow.com/a/23786928/5546916

ks1bbk
  • 31
  • 2
0

user "_has_items" , example: myarray_has_items willcheck the contion whether arry is empty or not then the tag wont render

or you can use {{#items.length}} to check length before render

{{#items.length}}
<ul>
    {{items}}
      <li>{{name}}</li>
    {{/items}}`enter code here`
</ul>

{{/items.length}}