Search code examples
javascriptjqueryjquery-templates

JQuery templates are not working with arrays


I am just learning Jquery templates and trying different things step by step. Now I tried it with single entry data element and it works fine. As far as I understand If I replace data with data array then it will show all the elements without using {each} tag. But in this case it is just erroring out. in Jquery. saying k.nodes is undefined.

Here is a small code snippet:

// my binding
$(document).ready(function () {
  $.tmpl("<div class = 'Test'>${Name}<div>", movies)
    .appendTo('#EmployeeContainer');
  $('#Template')
    .tmpl(movies)
    .appendTo('#EmployeeContainer');
});

// my data
var movies = [
  { Name: "The Red Violin", ReleaseYear: "1998" },
  { Name: "Eyes Wide Shut", ReleaseYear: "1999" },
  { Name: "The Inheritance", ReleaseYear: "1976" }
];

// part of my template from where Release year is coming
<script id = "Template" type ="text/templating">
  <div class = 'Test'>${ReleaseYear}<div>
</script>

Solution

  • It looks like you may have forgotten to compile the template.

    Take a look at the first example at jquery.com.

    Specifically, you need to call: $.template(...); to compile the template.

    You've already got the $.tmpl(...); part which renders the template. But, you need to compile it before rendering.

    Update: The main thing that was wrong is that you are missing the closing div in your template. You have <div> instead of </div> here's an updated working jsfiddle. Also, remember this is a plugin, so you need to download the plugin.