Home > Web Front-end > JS Tutorial > Creating HTML Templates with Mustache.js

Creating HTML Templates with Mustache.js

尊渡假赌尊渡假赌尊渡假赌
Release: 2025-02-24 09:35:11
Original
483 people have browsed it

Creating HTML Templates with Mustache.js

Web applications usually use MVC architecture to separate business logic from presentation views. Complex projects involve a large number of client HTML that uses JavaScript operations, which can be difficult to maintain. In this case, we can use a template system to improve reusability and simplify view management tasks. Mustache.js provides a well-documented template system that can be used to manage templates. Moreover, since Mustache supports multiple languages, we do not need to use a separate template system on the server side. This article describes the basics of using Mustache.

Key Points

  • Mustache.js is a well-documented template system that can be used to manage HTML templates in complex web applications, improve reusability and simplify view management tasks.
  • Mustache.js is illogical, meaning its template does not contain any if-else conditions or for loops. It uses labels denoted by double braces to add data to the template.
  • Mustache templates can be defined in a number of ways, including inline methods, inline scripts, and external HTML snippets. Which method to choose depends on the specific needs of the project.
  • Mustache.js is a multi-function tool that can be used on both the client and the server side and supports multiple languages. It also comes with tags for managing complex templates such as variables, sections, functions, and partial templates.

Why do we need a template system?

Most developers who don't know about template systems create new HTML blocks of code and dynamically insert them into the DOM using JavaScript. A common method is to specify the HTML element as a string, then set the innerHTML property or call the jQuery html() method. Here is an example:

var dynamic_html = "<div>HighlightedAuthor</div>";

document.getElementById("container").innerHTML = dynamic_html;</pre>
Copy after login
Copy after login
Copy after login

Another way to build a DOM is to create elements and append them separately, as shown below:

var title = document.createElement('div');
var highlight = document.createElement('span');
var highlight_text = document.createTextNode("Highlight");
var author = document.createElement('span');
var author_text = document.createTextNode("Author");
var container = document.getElementById('container');

highlight.appendChild(highlight_text);
title.appendChild(highlight);
author.appendChild(author_text);
title.appendChild(author);
container.appendChild(title);</pre>
Copy after login
Copy after login
Copy after login

Both of the above methods can effectively add elements to the document dynamically. Consider a situation where we have a well-designed bullet list that needs to be used in three different types of pages of the website. Using these techniques, we will have to repeat the list of HTML code in three different locations. This is often considered a bad coding habit. In this case, we can use predefined templates in different locations without duplicating the code. Mustache.js is a very popular JavaScript template engine. Since Mustache offers server-side and client-side templates in multiple languages, we don't have to worry about choosing a separate template engine.

Beginner of Mustache.js

Mustache is an open source logic-free template system suitable for languages ​​such as JavaScript, Ruby, Python, PHP, and Java. You can access the official page on GitHub to get a copy of the library. Mustache uses templates and views as the basis for creating dynamic templates. The view contains the JSON data to include in the template. A template contains presentation HTML or data with template tags that contain view data. We mentioned earlier that Mustache is illogical. This means that the template does not contain any if-else conditions or for loops. Now, let's get started with the Mustache template with a simple example.

var dynamic_html = "<div>HighlightedAuthor</div>";

document.getElementById("container").innerHTML = dynamic_html;</pre>
Copy after login
Copy after login
Copy after login

First, we need to include the mustache.js file in the document. Then we can start creating the Mustache template. In the example above, we have a view containing a person's name and occupation. We then use tags that present the code and name and career data within the render() function. Labels are represented by double braces or beards surrounding them. Now let's see how the render() method works.

Rendering Mustache template

The following code shows the implementation of the render() function in the mustache.js file. Three parameters can be passed to render(). The first two parameters template and view are required. Partials can be considered as dynamic templates that you can inject into the main template. In our previous example, we passed the template as an inline parameter, the view as a second parameter, and assign the result to the output variable.

var title = document.createElement('div');
var highlight = document.createElement('span');
var highlight_text = document.createTextNode("Highlight");
var author = document.createElement('span');
var author_text = document.createTextNode("Author");
var container = document.getElementById('container');

highlight.appendChild(highlight_text);
title.appendChild(highlight);
author.appendChild(author_text);
title.appendChild(author);
container.appendChild(title);</pre>
Copy after login
Copy after login
Copy after login

This is the most basic form of templated using Mustache. Let's take a look at other methods that can be used to create more canonical code.

Definition Mustache Template

There are several ways to define Mustache templates in your application. These methods are similar to using inline styles, inline stylesheets, and external stylesheets to include CSS. The example we discussed earlier can be considered an inline method because we pass the template directly to the function. This method prevents the possibility of reusable templates. Let's see how to define a template as an inline script template instead of passing it directly to a function.

Template as inline script

We can go to </pre>

You can include as many templates with different IDs in the document as you want. When you want to use a template, use innerHTML to get the HTML inside the script tag and pass it as a template. Our first example will be changed to the following code:
<!DOCTYPE html>
<html lang="en">
<head>
  <title>Mustache.js Inline Method</title>
  <🎜>
</head>
<body>
  <🎜>
  <p id="person"></p>
</body>
<🎜>
</html></pre>
Copy after login

As you can see, the template is stored separately and used dynamically when needed. This method increases the possibility of reusing templates. However, using inline scripts will limit the scope of the template to one page. If you have multiple pages, you must define the template again. So including templates in external files would be the ideal solution – just like CSS.

Template as external HTML snippet

In this technique, we will use jQuery to implement templates. jQuery provides a function called load() that can be used to get part of an external document. We will use this method to load the template dynamically from the external template file. The load() function executes scripts instead of returning them, so we cannot create templates inside script tags like we did in the previous method. The following example shows the external template file we will use.

var dynamic_html = "<div>HighlightedAuthor</div>";

document.getElementById("container").innerHTML = dynamic_html;</pre>
Copy after login
Copy after login
Copy after login

We have used the <div> element instead of scripts for templates to make it compatible with jQuery's load() function. Here we have three different templates with three different IDs. Now, let's continue to use these templates in your page.

var title = document.createElement('div');
var highlight = document.createElement('span');
var highlight_text = document.createTextNode("Highlight");
var author = document.createElement('span');
var author_text = document.createTextNode("Author");
var container = document.getElementById('container');

highlight.appendChild(highlight_text);
title.appendChild(highlight);
author.appendChild(author_text);
title.appendChild(author);
container.appendChild(title);</pre>
Copy after login
Copy after login
Copy after login

jQuery inserts the returned document into an HTML element instead of assigning it to a variable. Therefore, we need a virtual container to hold the template. I've used the template container that is hidden by default. The above example retrieves template1 and loads it. We can then get the template from the virtual container and pass it to Mustache for rendering. This is how external methods work. We can also use AJAX request to get data from the server.

Conclusion

Template engines and frameworks are very important for managing complex systems with dynamically changing presentation views. Mustache.js is one of the best choices for admin templates on the client side. We explain at the beginning of this tutorial why templates are important. Then, we continue to introduce various techniques using Mustache templates. You will now be able to choose a way to implement the Mustache template in your project. We've done exploring various techniques for using Mustache templates, but Mustache also comes with tags such as variables, sections, functions, and partial templates that are used to manage complex templates. Discussing the syntax for each tag is beyond the scope of this tutorial. You can find a comprehensive guide to the Mustache tag on the Mustache GitHub page. Feel free to share your previous experience with Mustache.js!

Mustache.js FAQ (FAQ)

  • What is the main difference between Mustache.js and other JavaScript template libraries?

Mustache.js is a logical template syntax. This means it can be used for HTML, configuration files, source code—anything. It works by extending labels in templates using the hash or values ​​provided in the object. Unlike other JavaScript template libraries, Mustache.js does not contain any if statements, else clauses, or for loops. Instead, it has only labels. Some tags are replaced with a value, some have nothing, others are a series of values.

  • How to use Mustache.js for HTML templates?

To use Mustache.js for HTML templates, you first need to include the Mustache.js script in the HTML file. Then, you define a template within the <script></script> tag. This template can contain placeholders to insert data. These placeholders are represented by double braces, such as {{name}}. You then use the Mustache.render() function to render the template with the data you provided.

  • Can I use Mustache.js with Node.js?

Yes, you can use Mustache.js with Node.js. To do this, you need to install the mustache package using npm. Once the installation is complete, you can need it in the Node.js file and use it to render the template.

  • How to use Mustache.js to traverse arrays?

In Mustache.js, you can traverse the array using the {{#array}}…{{/array}} syntax. Within this block, you can use {{.}} to reference the current item in the array. This allows you to display each item in the array in the template.

  • How to use conditional statements in Mustache.js?

While Mustache.js is a logically unlogic template library that does not support traditional if statements, you can still use sections to get similar results. Sections render text blocks once or more times based on the value of the key in the data object.

  • How to include some templates in Mustache.js?

Some templates in Mustache.js allow you to include smaller templates in a larger template. This is very useful for reusing common elements such as headers and footers. To include partial templates, you can use the {{>partial}} syntax.

  • How to escape HTML in Mustache.js?

By default, Mustache.js escapes HTML in the data to prevent XSS attacks. If you want to render HTML from your data, you can use triple brace syntax, such as {{{html}}}.

  • Can I use Mustache.js for the server side?

Yes, you can use Mustache.js for the server side. This is useful for rendering templates before sending them to the client, reducing the amount of JavaScript that needs to be executed on the client.

  • How to precompile a template in Mustache.js?

Precompiling templates in Mustache.js can improve performance by reducing the work that needs to be done at runtime. To precompile a template, you can use the Mustache.parse() function.

  • How to debug Mustache.js template?

Debugging the Mustache.js template can be tricky because the library does not provide a lot of error messages. However, you can use the Mustache.parse() function to check if your template is valid. This function returns an array of tags that you can check to see if your template structure is correct.

The above is the detailed content of Creating HTML Templates with Mustache.js. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template