Underscore JS template engine sample

11 Mar 2016

A shift in template rendering

The traditional way of rendering content has been shifted significantly with the personal computer becomes more and more powerful. Most of the old school framework relies on server side scripting for logic and composing the HTML content.

However, as the client side resource become more available with faster CPU and more RAM, we have seen a shift in delegating the front-end rendering duty to the client rather than processing it on the server, of course, if the logic allows.

There are quite a few JS front-end frameworks capable of performing front-end templating, to name a few


Why _.js

As I set myself on discover the framework that can deliver template engine, I also try to find a solution that help me de-couple and reduce the number of JS framework needed for my project. _.js qualifies that requirement with an extensive utlity library underneath and its templating engine. I find myself using its debounce, throttle, and of-course the loop functionality in a lot of situation.


Underscore sample usage

Let’s display a list of 5 English Premier League club and its manager.

<!-- Template scripting -->
<script type="text/template" id="template-1">
    <table>
        <th>
            <td>Club</td>
            <td>Manager</td>
        </th>
        <% _.each(teams, function(team) { %>
            <tr>
                <td><%= team.name %></td>
                <td><%= team.manager %></td>
            </tr>
        <% }); %>
    </table>
</script>

<!-- HTML place holder for content inject -->
<div id="template-1-placeholder"></div>

<!-- Javascript that runs the template engining function -->
<script type="text/javascript">
    // Ideally this JSON is generated by server side scripting
    var eplTeams = {
        {
            'name': 'Chelsea',
            'manager': 'Guus Hiddink'
        },
        {
            'name': 'Arsenal',
            'manager': 'Arsene Wenger'
        },
        {
            'name': 'Manchester United',
            'manager': 'Louis van Gaal'
        },
        {
            'name': 'Leicester City',
            'manager': 'Claudio Ranieri'
        },
        {
            'name': 'Liverpool',
            'manager': 'Jurgen Klopp'
        }
    };
    
    // Generate template by vanilla JS and _.js
    document.getElementById('template-1-placeholder').innerHTML = _.template(document.getElementById('template-1').innerHTML, {variable: 'teams'})(eplTeams);
</script>

Code in action