mustache- front end html template rendering tools

Why rendering tools

To understand this issue, we look at a few examples:

//示例1
var b = { Id: "123", Name: "张三", Age: 14 }
var output = "学生学号:" + b.Id + " 学生名称:" + b.Name + " 学生年龄:" + b.Age

//示例2
var list = [{ Id: "123", Name: "张三", Age: 14, Class: "", SubChild: [{ Id: "123", Name: "张三", Age: 14 }] }]
var html = "";
for (var i = 0; i < list.length; i++) {
    html = html + "<div class='" + list[i].Class + "' id='" + list[i].Id + "'>" + list[i].Name
    if (list[i].SubChild) {
        html += "<div>"
        for (var j = 0; j < list[i].SubChild; j++) {
            html += "<span>" + list[i].SubChild[j].Name + "</span>"
        }
        html += "</div>"
    }
    html += "</div>"
}

1 for example, we often encounter, due to the relatively simple, nothing much of a problem, do not think a better solution, for example 2, splicing at this time it is relatively complex, and if the greater amount of information, the more complex logic, this time, writing code is very complicated, and prone to error, is not conducive to maintenance, page rendering and code logic completely mixed together. How better solution exists scene two examples?

Template Rendering

We can write a line with the rules directly in the interface displays the html code and then enter the data into the template and rendering tools, there are rendering tools to generate html code out to meet the requirements, so the interface displays good logical separation, easy to maintain. mustache is such a rendering tools, project Address: https://github.com/janl/mustache.js

We look at a simple example (implementation example 2):

// html代码
{{ #list }}
        <div class="{{Class}}" id="{{Id}}">{{ Name }}
            {{#SubChild}}
            <div>{{ Name }}</div>
            {{/ SubChild}}
    </div>
{{ /list}}

//js 代码
var list = [{ Id: "123", Name: "张三", Age: 14, Class: "1class", SubChild: [{ Id: "123", Name: "张三sub", Age: 14 },{Name:"李四"}] }]
console.time("abc");
console.log(Mustache.render(template, { list: list }))
console.timeEnd("abc");

//输出结果
<div class="1class" id="123">张三
            <div>张三sub</div>
            <div>李四</div>
</div>

Can be seen from the above example, the logic is very simple to realize, it is also very easy to maintain, at the same time, the calculated time point of view, the speed is very fast, therefore, is very suitable for use in the rendering engine of front-end code

Guess you like

Origin www.cnblogs.com/zp900704/p/11721727.html