Site icon TechTricky: A Technology Blog on HTML, CSS, JQuery, Webaps and How to\'s

jQuery Template Plugin

jQuery template plugin allows you to render template items into HTML DOM, template items are HTML markup or text. Basically, we can define HTML markup with template variables and replace these variables inside the DOM when you get the data from an Ajax call or local static data.

Here is the simple example to display name and email list from static data.

<html>
<head>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
    <script src="http://ajax.aspnetcdn.com/ajax/jquery.templates/beta1/jquery.tmpl.js"></script>
</head>
<body>
 
    <table border="1" width="300">
        <thead>
        <tr>
            <th>Name</th>
            <th>Email</th>
          </tr>
        </thead>
        <tbody id="name-list"></tbody>
    </table>
 
       
    <script id="name-template" type="text/x-jquery-tmpl">
        <tr>
            <td>${name}</td>
            <td>${email}</td>
          </tr>
    </script>
    
    <script type="text/javascript">
        
        var data = [
                {"name":"Name1", "email":"a@email.com"},
                {"name":"Name2", "email":"b@email.com"},
                {"name":"Name3", "email":"c@email.com"},
                {"name":"Name4", "email":"d@email.com"}
             ];
        
        $(function() {
            $("#name-template").tmpl(data).appendTo("#name-list");
        });
    </script>
</body>
</html>

See the below output from above code:

NameEmail
Name1a@email.com
Name2b@email.com
Name3c@email.com
Name4d@email.com

It will replace the template variables (${name},${email) with actual data and inject the markup into the table body.
In the above example, we defined the data locally, but in reality this should get by using an Ajax request to a page or remote service.

See more examples and documentation here:
http://api.jquery.com/category/plugins/templates/
http://api.jquery.com/jquery.tmpl/
https://github.com/jquery/jquery-tmpl

Note: This feature and its documentation are in beta and subject to change before final release.

Exit mobile version
Close Bitnami banner
Bitnami