NJL Heavy Industries

Easy JavaScript Templates


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

        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">

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

<table id="output" class="table table-striped">
            <th>Name Length</th>

<script type="text/javascript">
        $('#click-for-template').on('click', function(ev){
            var name = prompt("Username");
            $('#output tbody').append(

...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.