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

Creating HTML Templates with Mustache.js

Feb 24, 2025 am 09:35 AM

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

The Evolution of JavaScript: Current Trends and Future Prospects The Evolution of JavaScript: Current Trends and Future Prospects Apr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

Is JavaScript hard to learn? Is JavaScript hard to learn? Apr 03, 2025 am 12:20 AM

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

How to implement panel drag and drop adjustment function similar to VSCode in front-end development? How to implement panel drag and drop adjustment function similar to VSCode in front-end development? Apr 04, 2025 pm 02:06 PM

Explore the implementation of panel drag and drop adjustment function similar to VSCode in the front-end. In front-end development, how to implement VSCode similar to VSCode...

See all articles