Recently, a 20-Year-Old developer Jack Franklin recommended five popular JavaScript template engines to developers in The article The top 5 JavaScript templating engines. The following is the translation of this document.
When creating a JavaScript Application, you must use a JavaScript template. When updating HTML, you can use templates instead of libraries (such as jQuery). Using templates can greatly simplify your code. This article will illustrate some popular template libraries.
1. Mustache
Mustache is often called the basis of JavaScript templates. Another popular solution, Hanldebars, is actually built based on Mustache. This does not mean that Mustache is a bad template solution. The following is an example:
Mustache. render ("Hello, {name}", {name: "Jack"}); // return: Hello, Jack
Once the page contains Mustache, you can access the global object "Mustache ". You can use the main method "render", which contains two parameters. The first parameter is the actual template, and the second parameter is the parameter value to be passed in.
In the above example, you can see "{name }}". "{}" Is actually the syntax of Mustache, indicating a placeholder. When Mustache compiles the object, it searches for the "name" attribute in the input object and uses the value of this attribute ("Jack" in this example ") to replace "{name }}".
Here, the template is only a string, but if you have a more complex template, this method may not work. The common solution is to place the template in the "script" tag:
<script type="text/x-mustache" id="template"> <p>Hello, {{name}}</p> </script>
Then, we can access the content of the script tag. For example, jQuery is easy to implement:
Var temp = $ ("# template" cmd.html (); Mustache. render (temp {name: "Jack"}); // return: <p> Hello, Jack </p>
To give "script" A "type" attribute that cannot be understood by the browser, the browser ignores the Script and does not use it as JavaScript or execute it.
You can also use loops in the template, as shown in the following template:
{{#people}} {{name}}{{/people}}
Transmit data:
{ people: [ { name: "Jack" }, { name: "Fred" } ] }
You will get the "JackFred" string.
Mustache has more features. Click here to view details.
2. Underscore Templates
Underscore provides a variety of useful methods and simple templates. Its syntax is slightly different from that of Mustache. The following is a simple case:
_. Template ("Hello, <% = name %>", {name: "Jack"}); // return: Hello, Jack
If you have used Embedded Ruby (abbreviated as ERB), you will be more familiar with this syntax. "<% = Name %>" indicates that no matter what value "name" is, it should be output at the "<% = name %>" position. Underscore also has loops and condition statements, but it is slightly different from Mustache.
var template = "<% _.each(people, function(name) { %> <li><%= name %></li> <% }); %>"_.template(template, { people: ["Jack", "Fred"] } );
In the Underscore template, you can insert any JavaScript in "<%>. Note: "<% = %>" is used for output, and <%> is used to include JavaScript. This means that any form of loops and conditional statements you use in JS can also be used in Underscore.
For more functions of Underscore, click here.
3. Embedded JS Templates
Embedded JS (EJS) comes from the ERB template and has many similarities with ERB. It has the same Tag as ERB and contains many identical functions.
In particular, you need to save the template in a separate file and pass the file name to EJS. It loads the file and returns HTML.
// In template. ejs Hello, <% = name %> // in JS file new EJS ({url: "template. ejs "}). render ({name: "Jack"}); // return: Hello, Jack
Note: you can load a Text Template:
new EJS({ text: "Hello, <%= name %>" }).render({ name: "Jack" });
The following describes how to loop. Take the array "People" as an example and link to their personal pages on the website:
// template.ejs <ul> <% for(var i = 0; i < people.length; i++) { %> <li><%= link_to(people[i], "/profiles/" + people[i]) %></li> <% } %> </ul>// in JS filenew EJS({ url: "template.ejs" }).render({ people: [ "Jack", "Fred" ] })// Each rendered <li> will look like:<li><a href="/profiles/Jack">Jack</a></li>
This is similar to Underscore, but pay attention to the use of "link_to. It is a Helper defined by EJS, so that the link is easier to use.
For more information about EJS, see the official website of EJS.
4. HandlebarsJS
Handlebars is one of the most popular template engines built on Mustache. The Mustache template also applies to the Handlebars template. At the same time, Handlebars also adds a lot of Helper. One of them is "".
// with this template: var source = "{{#with author}}
Note that the Handlebars compiler works in a slightly different way. First, you pass the template to "Handlebars. compile", which returns a function. You pass the object that contains data to the function, which returns HTML. "{# With}" Helper gets an object and allows you to pass attributes to the object. However, it does not take the following form:
{{ author.firstName}} {{author.lastName}}
But the following form
{{#with author}} {{firstName}} {{lastName}} {{/with}}
This saves input, especially when you use it very frequently.
Handlebars also provides "each" Helper:
Var source = "{{# each people }}{{ name }{{/each }}"; var template = Handlebars. compile (source); var html = template ({people: [{name: "Jack" },{ name: "Fred"}]}); // return: "JackFred"
In addition, you can use your own methods to extend Handlebars. The specific methods can be used in this document.
5. Jade templating
With the popularity of Node. js and the construction of a large number of Web applications, many templates have been designed for server. The Jade template is different from the one we have seen so far. It relies on a large number of indentation and spaces. The following is an example:
// template.jade p | Hello, = name// JS jade.renderFile("template.jade", { name: "Jack" }, function(err, result) { console.log(result); // logs: Hello, Jack });
The first time you see Jade, it may make you uncomfortable, but you will soon adapt to it. Two characters are indented under "p", indicating that these two characters exist in "p. "|" Is used to inform Jade that this line is plain text to be output; "=" is used to tell Jade to find a variable named "name.
We can also use loops in Jade:
each person in people li=person
Call up the storage name array: {people: ["Jack", "Fred"]}, which will output:
<li>Jack</li><li>Fred</li>
Jade has many functions not available in other templates. It can also do something like output Script labels:
script(type="text/javascript", src="myfile.js")
For more information about Jade templating, click here.
Here, we only illustrate the five most popular template engines. There are many other templates that you want to use to find the most suitable template engine. (Compilation: Chen qiuge grading: Xia mengzhu)
Original article: The top 5 JavaScript templating engines