31

Having a array like below

var arrNames = ["Stackoverflow","StackExchange","Webmaster","Programmers"];

how should a template look for working with mustache.js javascript template. I tried below but no clues

  • {{#}}{{key}}{{/}}

1 Answer 1

76

From the documentation:

When looping over an array of strings, a . can be used to refer to the current item in the list.

Template:

{{#musketeers}} * {{.}} {{/musketeers}}

View:

{ "musketeers": ["Athos", "Aramis", "Porthos", "D'Artagnan"] }

Output:

  • Athos
  • Aramis
  • Porthos
  • D'Artagnan

var tpl = document.getElementById('simple').innerHTML,
  view = {
    items: ['Stackoverflow', 'StackExchange', 'Webmaster', 'Programmers']
  };

document.getElementById('output').innerHTML = Mustache.to_html(tpl, view);
<script src="https://cdnjs.cloudflare.com/ajax/libs/mustache.js/2.3.0/mustache.js"></script>
<script type="template" id="simple">
  <h1>Array Values</h1>
  <ul>
    {{#items}}
    <li>{{.}}</li>
    {{/items}}
  </ul>
</script>

<div id="output"></div>

Sign up to request clarification or add additional context in comments.

3 Comments

Great answer! I was struggling to find it.
The fiddle seems to output nothing.
@DenisKniazhev updated to include runnable snippet here instead of jsFiddle

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.