JavaScript template engine overview

JavaScript template engine overview

In this article we will give an overview of JavaScript templates. We will first discuss what JavaScript templates are, when to use them, and how to use them. Before diving into more details, take a look at some popular template engines. We will focus on  Mustache Handlebars  and  jQuery Template .

What is a JavaScript template

JavaScript templates are a way to separate HTML structure from the content that contains them. The template system usually introduces some new syntax, but it is usually very simple, especially if we have used the template system elsewhere (such as Twig in PHP   ) before. An interesting point to note is that replacement tags are usually represented by double curly braces ({ {...} }), which is also the source of the names Mustache and Handlebars (hint: look at their similarities from the side).

When to use JavaScript templates?

Once we find ourselves in the JavaScript string containing HTML, we should start to consider the possible benefits of JavaScript templates. When building a maintainable code base, separation of concerns is crucial, so any means that can help us achieve this goal should be explored. In front-end web development, it is important to separate HTML from JavaScript (this is two-way, and we should not inline JavaScript in HTML).

Some common scenarios that can benefit from JavaScript templates are real-time web applications (such as an event commenting live broadcast application), or internationalization (i18n), which usually require the same format to display different content.

How to use JavaScript templates?

We will introduce it in detail through a special library case, but in essence it is as simple as including the library of our choice, namely obtaining a template and rendering it with some data.

Most libraries support inline and external templates. Inline templates are very suitable when there are few templates, or when every loaded page needs to use a template, but usually our template should be an external template. External templates bring many benefits, the main one is that templates will never be downloaded to the client unless they are required by the page.

mustache.js

Mustache  is a multilingual, logically simple template system. mustache.js is just one implementation. Once we get used to the (very simple) syntax, we can use it in a variety of programming languages.

key point

  • File size of 9kb (very small)
  • simple
  • No dependence
  • No logic
  • Non-precompiled templates
  • Programming language independent

For example