Search code examples
phpmustache

PHP arrays + Mustache templates


In PHP, I’m generating a simple array (list) to provide to the Mustache renderer. The array looks something like this:

Top-level Array ( 
    [times] => Array (
        [0] => Array (
                [hour] => 00
                [min] => 00
                [time] => 12am
            )

        [1] => Array (
                [hour] => 00
                [min] => 15
                [time] => 12:15am
            )

        [2] => Array (
                [hour] => 00
                [min] => 30
                [time] => 12:30am
            )
     )
)

The template looks like this:

<select>
    {{ #times }}
    <option value='{{hour}}{min}}'>{{time}}</option>
    {{ /times }}
</select>

No data is being inserted into the template. I've tried various combinations of {{ . }} and {{ .hour }}, etc inside the {{ #times }}{{ /times }} iterator. I've also tried using PHP’s ArrayIterator class, with no luck.


Solution

  • The correct syntax would be {{#times}} without spaces around and, as @BrettSantore noticed, one bracket is missing around min.

    <select>
        {{#times}}
        <option value='{{hour}}{{min}}'>{{time}}</option>
        {{/times}}
    </select>