Question

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!

Was it helpful?

Solution

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}}

OTHER TIPS

You can use the implicit iterator feature of mustache for this:

https://github.com/bobthecow/mustache.php/tree/master/examples/implicit_iterator

{{#values}}
    {{.}}
{{/values}}

Your original array probably needs numeric keys and now string though. It might work that way, but I haven't tested it.

I was working on a super old php framework, which was using smarty like syntax but double curly braces, kept me hanging for quite sometime, so the following made the loop run for me :) maybe it will help you too.

{{ #each link in bluelinks }}
  <p><strong>{{ link }}</strong></p>
{{/each}}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top