phpmustachemustache.php

Iterate through an array of arrays with Mustache


I have checked all similar questions, no one seem to have answered this.

$data = ['data' => array(
    ['id'=>'1','name'=>'Dupe', 'country' => 'Nigeria'], 
    ['id'=>'3','name'=>'Dipo', 'country' => 'Togo']
)];

$mustache->render('index', $data);

index.html looks like this:

<div>Hello</div>

<br>

<h2>Search for a person</h2>
<form action="/search" method="POST">
    Input user's name or email:
    <br><input type="text" name="key" value="" required>
    <br>
    <input type="submit" value="Search">
</form>

{{ #data }}
    <div> {{ name }} - {{ country }} </div>
{{ /data }}

It is currently returning a blank page.


Solution

  • I couldn't figure that out, but converting the inner array to objects works just fine:

    $m = new Mustache_Engine();
    $data = [
        'data' => array(
            ['id' => '1', 'name' => 'Dupe', 'country' => 'Nigeria'],
            ['id' => '3', 'name' => 'Dipo', 'country' => 'Togo']
        )
    ];
    $data = json_decode(json_encode($data));
    
    echo $m->render(
        '{{#data}}
           <div> {{ name }} - {{ country }} </div>
        {{/data}}',
        $data
    );
    

    This outputs:

    <div> Dupe - Nigeria </div>
    <div> Dipo - Togo </div>

    Notice {{#data}} and {{/data}} have no spaces!

    I've used an inline template string as i didn't have yours.