search
HomeWeb Front-endJS TutorialCreating HTML Templates with Mustache.js

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;

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);

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;

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);

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

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>

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;

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. <pre class='brush:php;toolbar:false;'>var title = document.createElement('div'); var highlight = document.createElement('span'); var highlight_text = document.createTextNode(&quot;Highlight&quot;); var author = document.createElement('span'); var author_text = document.createTextNode(&quot;Author&quot;); var container = document.getElementById('container'); highlight.appendChild(highlight_text); title.appendChild(highlight); author.appendChild(author_text); title.appendChild(author); container.appendChild(title);</pre> <p>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. </p> <p><strong>Conclusion</strong></p> <p>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! </p> <p><strong>Mustache.js FAQ (FAQ)</strong></p> <ul> <li><strong>What is the main difference between Mustache.js and other JavaScript template libraries? </strong></li> </ul> <p>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. </p> <ul> <li><strong>How to use Mustache.js for HTML templates? </strong></li> </ul> <p>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 <code><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
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
Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor