Search code examples
javascriptunderscore.jshandlebars.jsmustache

Rendering template data with Mustache.js in array of objects


I am using mustache.js to render template for 2 user data. Due to some error I am unable to get result, though for a single object I got results. Can someone help?

<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-alpha1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/mustache.js/2.1.3/mustache.js"></script>
<script>
$(document).ready(function(){
    $('button').click(function(){
        loadUser();
    });
});
</script>
</head>
<body> 
<button>Click Me!</button>
<div id="target"></div>

<script>
function loadUser() {
  var template = $('#template').html();
  var jdata = [{name: "Luke", age:"43"},{name:"Lara",age:"19"}];
  var rendered = Mustache.render(template, jdata);
  $('#target').html(rendered);
}
</script>
<script id="template" type="x-tmpl-mustache">
<p>Hello {{ name }}! with age {{age}}</p>
</script>
</body>
</html>

Solution

  • You are getting this error because repeating expressions are missing in the mustache template. Use the code below instead for defining template.

    <script id="template" type="x-tmpl-mustache">
        {{#.}}<p>Hello {{name}}! with age {{age}}</p>{{/.}}
    </script>