Intro to JavaScript Template Engines
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