Easy JavaScript Templates

Apparently, I handle JavaScript templates a lot more simply than most.

TEMPLATES = {};
$(document).ready(function(){ 
    $('script[type="underscore/template"]').each(function(){
        var $this = $(this);
        TEMPLATES[$this.attr("id")] = _.template($this.text());
    });
});

This finds all of the script tags with a type of "underscore/template". It then compiles the contents of that script tag as an underscore template, which produces a function that takes a context object and returns a compiled string. Finally, that function is assigned to a property on the TEMPLATES global that matches the script tag's id attribute.

Here is a contrived example.

<script type="underscore/template" id="table_row">
    <tr><th><%-username.toUpperCase()%></th>
        <td><%-size%></td>
        <td><%-username%></td></tr>
</script>

<a href="#" id="click-for-template">Click To See Template Result Here</a>

<table id="output" class="table table-striped">
    <thead>
        <tr><th>NAME</th>
            <th>Name Length</th>
            <th>Name</th></tr>
    </thead>
    <tbody>
    </tbody>
</table>

<script type="text/javascript">
    $(document).ready(function(){
        $('#click-for-template').on('click', function(ev){
            ev.preventDefault();
            var name = prompt("Username");
            $('#output tbody').append(
                    TEMPLATES.table_row({username:name, 
                                            size:name.length}));
        });
    });
</script>

...and that example, working here:

Click To Add User
NAME Name Length Name

This approach has several benefits. You can just decide what templates to include in a page server side, and serve up the appropriate stuff. I weave these templates inline to my HTML, where appropriate, making the design flow easily. The template that will render out a part of a page lives right next to the base HTML it will be affecting, so I don't have to go groveling through a bunch of files to find the appropriate template.