M
M
Marat2012-09-18 14:28:48
Programming
Marat, 2012-09-18 14:28:48

Mustache - iterate over an associative array

Data

$data = array(
   'items' => array('елемент1', 'елемент2', 'елемент3', 'елемент4')
);


Sample
<ul>
{{#items}}
   <li> {{.}}
{{/items}}
<ul>


Result
<ul>
   <li> елемент1
   <li> елемент2
   <li> елемент3
   <li> елемент4
<ul>


- everything is clear and it works.

But if i have the following array
$data = array(
   'items' => array(
       'el1' => 'елемент1', 
       'el2' => 'елемент2', 
       'el3' => 'елемент3', 
       'el4' => 'елемент4', 
   )
);

How to display this case in the template (using a loop, of course) or why is it impossible?
PS / I know about lambda functions, but the rendering happens on the server.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Stanislav, 2012-09-18
@crackedmind

I don't know PHP very well. Therefore, I will show you JSON data.

$data = array(
   'items' => array(
       'el1' => 'елемент1', 
       'el2' => 'елемент2', 
       'el3' => 'елемент3', 
       'el4' => 'елемент4', 
   )
);

From this, if I'm not mistaken, you get this JSON structure
{
    "items": {
         "el1":"element1", "el2":"element2", "el3":"element3", "el4":"element4"
     }
}

And since items is an associative array and mustache cannot process them in a loop. To do this, you will need to make a template like this:
<ul>
{{#items}}
   {{#el1}}<li> {{el1}}{{/el1}}
   {{#el2}}<li> {{el2}}{{/el2}}
   {{#el3}}<li> {{el3}}{{/el3}}
   {{#el4}}<li> {{el4}}{{/el4}}
{{/items}}
<ul>

Which is not very flexible.
It's better to put it this way.
{
    "items": [
         {"el":"element1"}, {"el":"element2"}, {"el3":"element3"}, {"el4":"element4"}
     ]
}

and this pattern
<ul>
{{#items}}
   {{#el}}<li> {{el}}{{/el}}
{{/items}}
<ul>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question