Remember back in classic ASP how you were able to insert server data into the page using special <%= %> tags? JavaScript has gotten to the point now where it is capable of utilizing the same technique. Contributing factors include JavaScript’s increased use, its improved processing capabilities, and the trend to outsource computations and processing to the client’s web browser. You could write code yourself, but thanks to the proliferation of a number of outstanding JavaScript templating libraries, there’s really no need. In today’s article, we’ll learn how these libraries work as well as see some real code in action!
Why Use JavaScript Templates?
JavaScript templates are a way to separate the view (HTML structure) from the data (content). In front-end web development this is characterized by the two-way separation of HTML from JavaScript – no inline JavaScript in HTML and no HTML markup produced by JavaScript. Hence, JavaScript Templates’ intended usage should become apparent whenever we find ourselves outputting HTML within a JavaScript string. JavaScript Templates’ role in helping us maintain separation of concerns is highly important for building a maintainable codebase.
Popular JS Template Engines include:
- Mustache – written in many languages, including JS
- Handlebars.js
- jQuery Template
- doT
- Dust
- EJS
- Underscore
- Jade
- ECT
- Template7
- jTemplates
For the purposes of this article, examples will follow the Handlebars syntax.
When to Use JavaScript Templates
Some common scenarios which could benefit from JavaScript templates are:
- Loading all data from the server, such as in rich list displays
- Adding or updating new items in lists
- Anywhere you need to add new complex content to the page
- Anything that requires client side HTML rendering
- Real-time web apps (for example a live streaming app for stock quotes)
- internationalization (i18n), which will quite often require that different content is displayed using the same formatting.
All of these scenarios have in common that new items are created and injected into the page from the client.
How Template Engines Work
Typically, Template Engines take information encoded as JSON and render it according to an HTML template. For example, here’s an JSON representation of U.S. president George Washington:
{ "name": "Washington", "firstname": "George", "born": "1732", "death": "1799" }
Adding a Template Engine to your project is as simple as referencing the library from your HTML using a regular <script> tag. Many libraries provide a hosted version, which has the added benefit that the file might be cached in the visitor’s browser, if it was previously used by another website.
// From File <script src="template_engine.js"></script> // From a host <script src="https://cdnjs.cloudflare.com/ajax/libs/template_engine/2.0.0/template_engine.js"></script>
Once you have the library in place, the next step is to start writing templates. Adding templates to your page will differ based on the library that you are using; one way is to include them in <script> tags with a special type attribute. The browser won’t recognize the type value, so it will ignore the script. However, the Template Engine can access it via the DOM and read its contents.
The templates typically contain a mix of HTML and text, as well as special expressions to output data. Expression syntax can also vary, but most libraries follow the style established by the popular Mustache templating engine whereby expressions are wrapped in double or triple curly braces {{}} (hint: if you turn them sideways, you can see their striking resemblance to mustaches!). The HTML code provides an “anchor” where the template will be inserted:
<body> <!--This is our template. --> <!--Data will be inserted in its according place, replacing the brackets.--> <script id="president-template" type="text/x-handlebars-template"> <p>The first president of the United States was {{firstname}} {{name}}.</p> </script> <!--Your new content will be displayed in here--> <div class="anchor"></div> </body>
Expressions tell the Template Engine to include the value of variables or to execute helper functions. Templates need to be compiled to a JavaScript function before use. You can see the JS code below. It uses jQuery to make working with the DOM easier, but Template Engines do not require it:
$(function () { // Grab the template script var theTemplateScript = $("#president-template").html(); // Compile the template var theTemplate = Handlebars.compile(theTemplateScript); // Define our data object var president={ "name": "Washington", "firstname": "George", "born": "1732", "death": "1799" }; // Pass our data to the template var theCompiledHtml = theTemplate(president); // Add the compiled html to the page $('.anchor').html(theCompiledHtml); });
You can see today’s code in action (using the Handlebars library) on Codepen.io.
Conclusion
In an upcoming article, we’ll compare some of the popular JS Template Engines and explore some of the pros and cons of each.