Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing value of iterated field in Mustache PHP

Say I have an array in PHP that looks like so:

    $values = Array(
        '0' => 'value1',
        '1' => 'value2',
        '2' => 'value3'
    )

I'd like to iterate through the array using Mustache but I'd like the associated value. This is what I'm hoping to do:

    {{#values}}
        {{the current value}}
    {{/values}}

I hope there returned result would be:

    value1
    value2
    value3

I've been getting around this by changing my structure to:

    $values = Array(
        '0' => array('value=' =>'value1'),
        '0' => array('value=' =>'value2'),
        '0' => array('value=' =>'value3'),
    )

And call {{valule}} inside the Mustache iterator.

Should I be doing this a completely different way? I'm using a SplFixedArray in PHP and I'd like to iterate through the values using this method...

Thanks!

like image 253
pilotguy Avatar asked Feb 15 '12 21:02

pilotguy


1 Answers

The implicit Iterator is the way to go for simple data. If your data is more complex then PHPs ArrayIterator does the job well.

Here is an example that I have working. Hope it is useful for somebody else.

$simple_data = array('value1','value2','value3');   
$complex_data = array(array('id'=>'1','name'=>'Jane'),array('id'=>'2','name'=>'Fred') );

$template_data['simple'] = $simple_data;
$template_data['complex'] = new ArrayIterator( $complex_data ); 

$mustache->render('template_name', $template_data );

And in the template you could have

{{#simple}}
      {{.}}<br />
{{/simple}}

{{#complex}}
   <p>{{ id }} <strong>{{ name }}</strong></p>
{{/complex}}
like image 137
aberpaul Avatar answered Oct 16 '22 14:10

aberpaul