Search code examples
jqueryjquery-templates

jQuery Template issue - not rendering


i have the following template

<script id="employeeTemplate" type="text/html">
    <tr>
        <td>${Name}</td>
        <td>${Designation}</td>
        <td>{{if Age>30}}
            <span style='background-color: red'>Middle-aged</span>
            {{else}}
            <span style='background-color: yellow'>Still young</span>
            {{/if}}</td>
        <td>${Department}</td>
        <td>${DataSource}</td>
    </tr>
</script>

and the following functions

    <script type="text/javascript">
    function BindClientSideData() {
        //JSON data format
        var emps = [
        { Name: "John", Designation: "Analyst", Age: 25, Department: "IT", DataSource: "Client" },
        { Name: "Matthew", Designation: "Manager", Age: 38, Department: "Accounts", DataSource: "Client" },
        { Name: "Emma", Designation: "Senior Manager", Age: 40, Department: "HR", DataSource: "Client" },
        { Name: "Sid", Designation: "Analyst", Age: 27, Department: "HR", DataSource: "Client" },
        { Name: "Tom", Designation: "Senior Analyst", Age: 35, Department: "IT", DataSource: "Client" }
        ];
        BindTable(emps);
    }

    function BindTable(data) {
        // removes existing rows from table except header row
        $('#tblEmployee tr:gt(0)').remove();
        //apply tmpl plugin to <script> and append result to table
      //  $("#employeeTemplate").tmpl(data).appendTo("#tblEmployee");
       $("#tblEmployee").loadTemplate("#employeeTemplate", data);
    }
</script>

The problem is that when BindClientSideData() is called, i get the following output

    ${Name} ${Designation} {{if Age>30}} Middle-aged {{else}} Still young {{/if}} ${Department} ${DataSource} 
${Name} ${Designation} {{if Age>30}} Middle-aged {{else}} Still young {{/if}} ${Department} ${DataSource} 
${Name} ${Designation} {{if Age>30}} Middle-aged {{else}} Still young {{/if}} ${Department} ${DataSource} 
${Name} ${Designation} {{if Age>30}} Middle-aged {{else}} Still young {{/if}} ${Department} ${DataSource} 
${Name} ${Designation} {{if Age>30}} Middle-aged {{else}} Still young {{/if}} ${Department} ${DataSource} 

Can someone please let me know why the temaplate is not loading data.

I am referencing the jQuery 19.2 and jQuery.tmpl.js

Tried changing syntax etc of jQuery temaplate but no luck. Any help appreciated.


Solution

  • Try:

    $("#tblEmployee").loadTemplate($("#employeeTemplate"), data);
    

    instead of

    $("#tblEmployee").loadTemplate("#employeeTemplate", data);
    

    here is an example with jquery tmpl with a different syntax.

    $.tmpl($('#employeeTemplate'), data).appendTo('#tblEmployee');
    

    Fiddle