preface

When we do front-end development, we often need to dynamically generate HTML according to the JSON data returned by the background and insert it into the page for display. The easiest way to do this is to iterate through the data concatenation HTML with jQuery, as follows:

<script>
    var data = {
        list: [{
            id: 1,
            name: 'zhangsan',
            email: '[email protected]'
        }, {
            id: 2,
            name: 'lisi',
            email: '[email protected]'
        }]
    };
    var html = '';
    $.each(data.list, function(index, item) {
        html += '<tr></tr>';
        html += '<td>' + item.id + '</td>';
        html += '<td>' + item.name + '</td>';
        html += '<td>' + item.email + '</td>';
        html += '</tr>'
    });
    $('#userList').empty();
    $('#userList').html(html); 
</script>
Copy the code

However, this method of concatenating HTML works fine for simpler structures; If the structure is complex, you have to pay attention to the nesting of quotes when stitching, and the code is difficult to maintain, and the code readability is poor. So using a template engine can help us avoid this problem.

Common template engines include artTemplate, Jade, Mustache, dot.js, juicer, etc. This article only introduces the use of dot.js.

introduce

DoT template Engine is the fastest and most concise JavaScript template engine available on both the browser side and the Nodejs side. It’s small, fast, and has no dependencies. All the code is just over a hundred lines, compressed in 4K, and very lightweight.

configuration

There is a templateSettings property in the doT file that is used to set the doT delimiter. We can also use our own delimiter manually, but the default is recommended:

doT.templateSettings = { evaluate: /\{\{([\s\S]+?) \}\}/g, interpolate: /\{\{=([\s\S]+?) \}\}/g, encode: /\{\{! ([\s\S]+?) \}\}/g, use: /\{\{#([\s\S]+?) \}\}/g, define: /\{\{##\s*([\w\.$]+)\s*(\:|=)([\s\S]+?) #\}\}/g, conditional: /\{\{\? (\? ? \s*([\s\S]*?) \s*\}\}/g, iterate: /\{\{~\s*(? :\}\}|([\s\S]+?) \s*\:\s*([\w$]+)\s*(? :\:\s*([\w$]+))? \s*\}\})/g, varName: "it", // control whitespace characters, true - remove all, false - keep strip: True, // Performance tuning setting, which adjusts performance, and setting append to false may produce better results: True, // If 'selfcontained' is true, doT will generate functions selfcontained: false, doNotSkipEncoded: false}; One of the attributes in the configuration is varName, which has a value of IT and represents the variable name used to pass objects into the template.Copy the code

If you want to use your own separators, change the re in doT. TemplateSettings to suit your needs.

Here is the default list of delimiters:

  • {{}} : evaluate

  • Interpolate {{=}} : Used for interpolation

  • {{! }} : for interpolation encoding (encode)

  • {{#}} : used to evaluate/include local templates at compile time (use)

  • {{## #}} : used for compile-time definition

  • {{? }} : for conditional statements

  • {{~}} : used for array iteration (iterate)

The basic grammar

We’ll start with the use and meaning of the delimiter representation commonly used in doT templates:

= {{}} output shows that the default variable name it (for interpolation) {{}} template notation {{(used for evaluation)? }} conditional branch, short for if condition (conditional statement) {{~}} conditional statement (array iteration) {{! }} encoded output display (for encoding evaluation) {{#}} for compile-time evaluation/import and local template {{## #}} for compile-time definitionCopy the code

Template sample

<! - assignment -- -- > < script id = "interpolationtmpl" type = "text/x - dot - the template" > < div > {{= it. The name}} < / div > < div > dot framework < / div > < / script > <! <script id="evaluationtmpl" type="text/x-dot-template"> {{for(var prop in it) {} {{= it[prop]}}</div> {{}}</ script> <! <script id="arraystmpl" type="text/x-dot-template"> {{~it. Interests :value:index}} <div> subscript: {{= index}} {{= value }}! </div> {{~}} </script> <! <script id="conditionstmpl" type="text/x-dot-template"> {{? {{=it. Name}} <div>name exists when it goes here, {{=it. </div> {{?? ! Age === 0}} <div>age = 0 </div> {{?? }} You are {{=it.age}} {{? }} </script>Copy the code

Looping array example

An array of

Var allData = [' guangzhou ', 'shenzhen', zhuhai, shantou, foshan, shaoguan, heyuan, meizhou city, 'huizhou', 'shanwei cities',' city ', 'in zhongshan, jiangmen, yangjiang, zhanjiang, Maoming city, Zhaoqing City, Qingyuan City, Chaozhou City, Jieyang City, Yunfu City];Copy the code

Number converts the prop string to a Number

<script id="dot_01" type="text/x-dot-template">
    <ul>
        {{ for(var prop in it) { }}
        <li class="nav-item" id="nav_{{=Number(prop)+1}}">{{= it[prop] }}</li>
        {{ } }}
    </ul>
</script>
Copy the code

Conditional statement example

In the template sometimes we need to judge the data, display different, we need to use conditional delimiters.

<script id="templ4" type="text/x-dot-template"> <div> Name: {{=it. Name}} {{= it. Score}} < / div > {{? It. Score < 60}} < div > level: failed < / div > {{?? It. Score < 70}} < div > level: pass the < / div > {{?? It. Score < 80}} < div > level: Good < / div > {{?? It. Score < 90}} < div > level: excellent < / div > {{?? It. Score < 100}} < div > level: great < / div > {{?}} < div > level: </div> {{?}} </script>Copy the code

For the condition, we can also use the evaluation delimiter to rewrite the above:

<script id="templ4" type="text/x-dot-template"> <div> Name: {{=it. Name}} {{= it. Score}} < / div > {{if (it) score < 60) {}} < div > level: failed < / div > {{} else if (it) score < 70) {}} < div > level: Pass the < / div > {{} else if (it) score < 80) {}} < div > level: good < / div > {{} else if (it) score < 90) {}} < div > level: Good < / div > {{} else if (it) score < 100) {}} < div > level: great < / div > {{} else {}} < div > level: data wrong < / div > {{}}} < / script >Copy the code

Examples of difficulties in the project

{{=it[0].titlecn}}
{{=it[1].titlecn}}
{{=it[2].titlecn}}
{{=it[3].titlecn}}
{{=it[4].titlecn}}
Copy the code

Image rendering (ternary judgment)

<img src="{{=it[0].logo? it[0].logo:'img/kan/04.png'}}">Copy the code

Use method in dot template

src="{{=setICon_opShowflag(value.opShowflag)}}"
{{=estriction(it[7].titlecn,19)}}
Copy the code