Geeks With Blogs
Liam McLennan hackingon.net

Why Use Client-side Javascript Templates?

When building rich internet applications you often need to construct html on the client. I am going to demonstrate how to construct DOM elements using the jqote jQuery plugin (2.0.0).

The naive approach to client-side html generation is to embed html inside javascript like:

var text = 'Some text';
$('body').append($('<div id="content>' + text + '</div>"'));

This approach fails as the complexity of the html increases. It is also a clear separation of concerns violation to mix html (presentation) with script (interaction).

Javascript templates provide a way to dynamically build html on the client while storing the dynamic html with the rest of the presentation markup. Additionally javascript templates provide MVC-like separation of concerns.

Dynamically Building a Table with a Client-side Javascript Template

Suppose you want a web page that allows the user to build a table of people. For each person the user can enter their name and age. First we need a form to collect the values, and we need some jQuery magic to cancel the form post:

<form id="people_input">
        <label for="name">Name: </label><input type="text" name="name" /><br />
        <label for="age">Age: </label><input type="text" name="age" /><br />
        <input type="submit" value="Add" />
    </form>

    <script type="text/javascript">

        $(document).ready(function () {

            $('form#people_input').submit(function (e) {
                e.preventDefault();
            });

        });    
    
    </script>

There needs to be a table to display the people, and each time the form is submitted a new row should be added to the table. jqote templates are defined in the html by wrapping the template in a script tag and a CDATA tag. The script tag is necessary to stop the template from being interpreted as part of the page. The CDATA tag is required so that the page remains syntactically valid. Here is my empty table and a template for a row:

<table id="person_table">
        <tr>
            <th>Name</th><th>Age</th>
        </tr>    
    </table>

    <script type="text/html" id="template">
    <![CDATA[
        <tr>
            <td><$= this.name $></td><td><$= this.age $></td>
        </tr>    
    ]]>
    </script>

The default jqote tags use <%= %> syntax which I have replaced with <$= $> to avoid conflict with Asp.Net MVC. Inside of a jqote template ‘this’ refers to the data object used to render the template. Within the jqote tags any javascript is valid since jqote is based on John Resig’s Javascript Micro-Templating.

The final, and most interesting step is to render the template each time the form is submitted and insert the result at the end of the table. Note the second parameter to the jqote() method, which is the character to use for the html nugget syntax.

        $(document).ready(function () {

            $('form#people_input').submit(function (e) {
                var data = { name: $('input[name=name]').val(), age: $('input[name=age]').val() };
                $('table#person_table').append($('#template').jqote(data, '$'));
                e.preventDefault();
            });

        });   

To try out the complete code, grab it from codepaste.net.

Posted on Wednesday, March 3, 2010 1:57 AM | Back to top

Copyright © Liam McLennan | Powered by: GeeksWithBlogs.net