Detailed description of the Javascript template engine mustache. js_javascript skills

Source: Internet
Author: User
This article mainly introduces the Javascript template engine mustache. js, mustache. js is a simple and powerful Javascript template engine. It can be used to simplify html writing in js Code. After compression, it is only 9KB, which is very worthy of use in projects, if you need it, you can refer to this article to summarize its usage methods and some usage experiences. The content is not very advanced. It is purely an entry-level content. Just take a look. However, if you have not used such a javascript Engine library, this article is worth reading. I believe that after you understand its powerful functions and simple usage, you can't wait to use it for your work.

1. Start with a simple and realistic demand
At present, the company has developed a unified development platform. The backend encapsulates the MVC interface and the interface for adding, deleting, modifying, and querying data, I developed a development framework using bootstrap + hand-writing components on the front end. With CAS integrated, I first developed a unified permission management system based on CAS, this system is the first subsystem of our development platform. It is used to manage and configure the menus and authorizations of all subsystems and to manage the organization structure and users of the entire company, later, we developed business system A and business system B. Since these three subsystems correspond to three java projects, three applications are deployed in tomcat during the final deployment. One requirement is:

  • 1) After logging on to each system, click the system name. A drop-down menu is displayed, showing all subsystems with permissions;
  • 2) then, you can click another subsystem to switch to the selected system. After arriving at other systems, you can also switch back from the system because the drop-down menu is made;
  • 3) if the user has only one system permission, no drop-down menu is displayed.

The requirement is actually quite simple. The prototype is probably like this:

The function is implemented by calling the interface for obtaining the system list after logging on to each subsystem and rendering a drop-down menu in js. The format returned by this interface is:

Data: [{"sortOrder": 1, "isCurrent": true, "systemHttpUrl": "http: // xxxx: 8080/permission", "systemName ": "unified permission management system" },{ "sortOrder": 2, "isCurrent": false, "systemHttpUrl": "http: // xxxx: 8080/systemA ", "systemName": "business system A" },{ "sortOrder": 3, "isCurrent": false, "systemHttpUrl": "http: // xxxx: 8080/systemB ", "systemName": "Business System B"}]

If we do not use the template engine, the traditional method to parse the data and convert it into an html string is usually:

function data2Html(data) { data = data || []; var html = ['
 
 
    ', '
  • ', ' '], l = data.length; if(l < 2) { l == 1 && html.push(data[0].systemName || ''); html.push('
'); return html.join(''); } var curSysAry = data.filter(function(s){ return s.isCurrent; }); html.push(curSysAry[0].systemName + '
    '); data.sort(function(a, b){ return a.sortOrder - b.sortOrder;}); for(var i = 0; i < l; i++) { i && html.push('
  • '); html.push('
  • ' + data[i].systemName + '
  • '); } html.push('
'); return html.join('');}

This String concatenation method has many drawbacks:

  • 1) difficult, especially complicated splicing logic. The splicing string is long;
  • 2) It is not easy to maintain. If you do not care about it, the corresponding relationship of the tag will be wrong;
  • 3) The structure is unclear.

The tool that can simplify this scenario is the template engine, which is the first Technology backend in the template engine. If you have used jsp, you must know that jsp is a template used to parse and present data, other background template engines include velocity and freemarker. There are also many front-end template engines. mustache. js is a popular one, and git has over 8000 likes. If we use mustache. js to solve this problem, we can turn it into this:

// Use some tags corresponding to the attribute name to define the template var _ template = ['
 
 
    ','
  • ', '',' {CurSystemName }{{# multiple }}{{/ Multiple} ', '',' {{# multiple }}
      ',' {{# Systems }}', '{{ ^ first }}
    • {/First }}','
    • ',' {SystemName }}','
    • ',' {/Systems }}','
    {/Multiple }}','
  • ','
']. Join (''); // initialize the Mustache template. parse (_ template); function data2Html (data) {data = data | []; var curSysAry = data. filter (function (s) {return s. isCurrent;}); data. sort (function (a, B) {return. sortOrder-B. sortOrder;}); data = data. map (function (s, I) {s. first = I = 0; return s}); // The template is rendered as a string return Mustache. render (_ template, {curSystemName: curSysAry. length? CurSysAry [0]. systemName: '', multiple :!! Data. length, systems: data });}

Comparing the two codes, we will find the following code, which has the following advantages over the previous one:

  • 1) The structure is clear. All html to be rendered are defined in one position without any splicing;
  • 2) The logic is clear. The tags in the template actually correspond to the attribute names of the objects passed in during template rendering;
  • 3) easy to maintain. To add or delete tags, you only need to adjust the array corresponding to the template.

Through this example, we should be able to have a general understanding of the template engine. Such tools are becoming more and more common in front-end development, especially for front-end and back-end separation applications, it is already the content of the basic architecture of such applications. Mustache. js is a very easy-to-use engine implementation. The following content will introduce the commonly used template configurations of this tool and use them with practical examples. I hope you will like this tool more :)

2. Usage of mustache
The usage of mustache is very simple. first introduce its js file through the script tag, and then perform the following operations:
1) define the template string
There are two ways to define a template. The first method is as shown in the previous section. You can directly use [...]. the join ('') method is defined in js Code. method 2 defines the template content in html using a script:

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.