Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<pre><code>var model = [ {"1":{"name":"One","color":"red"}}, {"2":{"name":"Two","color":"green"}} ]; var model4view = {dots: model.map(function(obj){ var v; for (k in obj) {v = obj[k];}; return v; })}; template = "'&lt;ul&gt; {{#dots}} &lt;li&gt;{{name}} -- {{color}} &lt;/li&gt; {{/dots}} &lt;/ul&gt;'"; var html = Mustache.to_html(template, model4view); </code></pre> <p>AFAIK , with reference to the <a href="http://mustache.github.io/mustache.5.html" rel="nofollow">mustache manual page</a> <strong>Sections</strong> are the type of tags that allow to render blocks of text <strong>one or more times</strong>, but <strong>The behavior of the section is determined by the value of the key.</strong> so we need a key and a value that is the list. Therefore the array have to be the value of the key. </p> <p>In the above code I leverage <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map" rel="nofollow">Array.prototype.map()</a> to get a <code>model4view</code> which has a <strong>key</strong> with an arbitrary name: <code>dots</code> ( so we can use this name in mustache section tag <code>{{#dots}}</code> and a <strong>value</strong> that consist of the object value of the original <em>numberd array</em> item value. For example:</p> <pre><code>{"dots":[ {"name":"One","color":"red"}, {"name":"Two","color":"green"} ]} </code></pre> <p><strong>[EDIT]</strong> If you need to output also the numer associated with each item you can use a map function: </p> <pre><code>function(v){ for (var property in v) { o = v[property]; o['id'] = property; return(o); }}); </code></pre> <p>this way the number can be used in the template as <code>{{id}}</code>.</p> <p><a href="http://jsfiddle.net/rondinif/MdxNU/1/" rel="nofollow">Here is my <strong>fiddle</strong></a> where you can try and play around the solution.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload