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>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>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>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>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>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>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>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!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

JavaScript's garbage collection mechanism automatically manages memory through a tag-clearing algorithm to reduce the risk of memory leakage. The engine traverses and marks the active object from the root object, and unmarked is treated as garbage and cleared. For example, when the object is no longer referenced (such as setting the variable to null), it will be released in the next round of recycling. Common causes of memory leaks include: ① Uncleared timers or event listeners; ② References to external variables in closures; ③ Global variables continue to hold a large amount of data. The V8 engine optimizes recycling efficiency through strategies such as generational recycling, incremental marking, parallel/concurrent recycling, and reduces the main thread blocking time. During development, unnecessary global references should be avoided and object associations should be promptly decorated to improve performance and stability.

There are three common ways to initiate HTTP requests in Node.js: use built-in modules, axios, and node-fetch. 1. Use the built-in http/https module without dependencies, which is suitable for basic scenarios, but requires manual processing of data stitching and error monitoring, such as using https.get() to obtain data or send POST requests through .write(); 2.axios is a third-party library based on Promise. It has concise syntax and powerful functions, supports async/await, automatic JSON conversion, interceptor, etc. It is recommended to simplify asynchronous request operations; 3.node-fetch provides a style similar to browser fetch, based on Promise and simple syntax

JavaScript data types are divided into primitive types and reference types. Primitive types include string, number, boolean, null, undefined, and symbol. The values are immutable and copies are copied when assigning values, so they do not affect each other; reference types such as objects, arrays and functions store memory addresses, and variables pointing to the same object will affect each other. Typeof and instanceof can be used to determine types, but pay attention to the historical issues of typeofnull. Understanding these two types of differences can help write more stable and reliable code.

Hello, JavaScript developers! Welcome to this week's JavaScript news! This week we will focus on: Oracle's trademark dispute with Deno, new JavaScript time objects are supported by browsers, Google Chrome updates, and some powerful developer tools. Let's get started! Oracle's trademark dispute with Deno Oracle's attempt to register a "JavaScript" trademark has caused controversy. Ryan Dahl, the creator of Node.js and Deno, has filed a petition to cancel the trademark, and he believes that JavaScript is an open standard and should not be used by Oracle

Which JavaScript framework is the best choice? The answer is to choose the most suitable one according to your needs. 1.React is flexible and free, suitable for medium and large projects that require high customization and team architecture capabilities; 2. Angular provides complete solutions, suitable for enterprise-level applications and long-term maintenance; 3. Vue is easy to use, suitable for small and medium-sized projects or rapid development. In addition, whether there is an existing technology stack, team size, project life cycle and whether SSR is needed are also important factors in choosing a framework. In short, there is no absolutely the best framework, the best choice is the one that suits your needs.

IIFE (ImmediatelyInvokedFunctionExpression) is a function expression executed immediately after definition, used to isolate variables and avoid contaminating global scope. It is called by wrapping the function in parentheses to make it an expression and a pair of brackets immediately followed by it, such as (function(){/code/})();. Its core uses include: 1. Avoid variable conflicts and prevent duplication of naming between multiple scripts; 2. Create a private scope to make the internal variables invisible; 3. Modular code to facilitate initialization without exposing too many variables. Common writing methods include versions passed with parameters and versions of ES6 arrow function, but note that expressions and ties must be used.

Promise is the core mechanism for handling asynchronous operations in JavaScript. Understanding chain calls, error handling and combiners is the key to mastering their applications. 1. The chain call returns a new Promise through .then() to realize asynchronous process concatenation. Each .then() receives the previous result and can return a value or a Promise; 2. Error handling should use .catch() to catch exceptions to avoid silent failures, and can return the default value in catch to continue the process; 3. Combinators such as Promise.all() (successfully successful only after all success), Promise.race() (the first completion is returned) and Promise.allSettled() (waiting for all completions)

CacheAPI is a tool provided by the browser to cache network requests, which is often used in conjunction with ServiceWorker to improve website performance and offline experience. 1. It allows developers to manually store resources such as scripts, style sheets, pictures, etc.; 2. It can match cache responses according to requests; 3. It supports deleting specific caches or clearing the entire cache; 4. It can implement cache priority or network priority strategies through ServiceWorker listening to fetch events; 5. It is often used for offline support, speed up repeated access speed, preloading key resources and background update content; 6. When using it, you need to pay attention to cache version control, storage restrictions and the difference from HTTP caching mechanism.
