“This is the third day of my participation in the First Challenge 2022, for more details: First Challenge 2022”.

What is a template engine

A template engine is the most elegant solution for turning data into views. Data:

[{"name":"Xiao Ming"."age":12."sex":"m"},
  {"name":"Little red"."age":11."sex":"f"}]Copy the code

View:

<ul>
  <li>
  	<div>Basic information about Xiao Ming</div>
  	<div>
  	  <p>Name: Xiao Ming</p>
  	  <p>Age: 12</p>
  	  <p>Gender: male</p>
  	</div>
  </li>
</ul>
Copy the code

while

<li v-for="item in arr"></li>
Copy the code

Is a template engine!!

Historically, data has been transformed into views

Pure DOM method

Only after I wrote it myself did I realize that pure DOM methods are really complicated.

<body>
    <ul id="list"></ul>
    <script>
        let list = document.querySelector("#list");

        for (let index = 0; index < arr.length; index++) {
            let li = document.createElement("li");
            let infoDiv = document.createElement("div");
            infoDiv.className = "info";
            list.appendChild(li);
            li.appendChild(infoDiv);

            let p1 = document.createElement("p");
            p1.innerHTML = "Name:" + arr[index].name;

            let p2 = document.createElement("p");
            p2.innerHTML = "Age:" + arr[index].age;

            let p3 = document.createElement("p");
            p3.innerHTML = "Gender: + arr[index].sex;

            infoDiv.appendChild(p1);
            infoDiv.appendChild(p2);
            infoDiv.appendChild(p3);
        }
    </script>
</body>

Copy the code

An array of the join method

It’s just an array converted to a string. The browser converts the string into a DOM structure.

<body>
    <ul id="list"></ul>
    <script>
        let list = document.querySelector('#list')

        for (let index = 0; index < arr.length; index++) {
            list.innerHTML += [
                '<li>'.' 
        
'
.'

Name:'

+ arr[index].name + '</p>'.'

Age:'

+ arr[index].age + '</p>'.'

Gender:'

+ arr[index].sex + '</p>'.' '.'</li>' ].join(""); }
</script>
</body> Copy the code

ES6 backquotes

It’s essentially a concatenation, but it’s much nicer than an array. At the same time, you can add content to elements with ${}. Concatenation strings are no longer required.

<body>
    <ul id="list"></ul>
    <script>
       let list = document.getElementById("list");
        for (let index = 0; index < arr.length; index++) {
            list.innerHTML += `
                <li>
                    <div>
                        <p>Name: ${arr [index]. Name}</p>
                        <p>Age: ${arr [index]. Age}</p>
                        <p>Gender: ${arr [index] sex}</p>
                    >/div>
                </li>`}</script>
</body>

Copy the code

Mustache library is basically used

  • You have to use mustache libraries, which you can find packaged at bootcdn.com;
  • Using Mustache’s render method, the template and data are combined to produce a DOM structure that can be printed on the console.

Array of loop objects

<body>
    <ul id="list"></ul>
    <script src="jslib/mustache.js"></script>
    <script>Var templateStr = '<ul>
                {{#arr}}
                <li>
                    <div>
                        <p>Name:{{name}}</p>
                        <p>Age:{{age}}</p>
                        <p>Gender:{{sex}}</p>
                    </div>
                </li>
                {{/arr}}
            </ul>
        `;

        var domStr = Mustache.render(templateStr, data);
        console.log(domStr);

        let list = document.getElementById("list");
        list.innerHTML = domStr;
    </script>
</body>
Copy the code

Loop simple array

<body>
    <div id="list"></div>
    <script>
        var templateStr = `
            <ul>
                {{#arr}}
                <li>
                    {{.}}
                </li>
                {{/arr}}
            </ul>
        `;

        var data = {
            arr: ["a", "b", "c"],
        }

        var domStr = Mustache.render(templateStr, data);
        console.log(domStr);

        let div = document.querySelector("div");
        div.innerHTML = domStr;
    </script>
</body>
Copy the code

Don’t cycle

The < body > < div > < / div > < script > var templateStr = ` < h1 > {{day}} day is today, the weather {{weath}} < / h1 > `; Var data = {day: "", weath:" "}; var domStr = Mustache.render(templateStr, data); console.log(domStr); let div = document.querySelector("div"); div.innerHTML = domStr; </script> </body>Copy the code

Loop through nested arrays

The < body > < div id = "list" > < / div > < script > var templateStr = ` < ul > {{# arr}} < li > < p > name: {{name}} < / p > < p > age: {{age}} < / p > < p > gender: {{sex}}</p> <ol> {{#hobbies}} <li>{{.}}</li> {{/hobbies}} </ol> </li> {{/arr}} </ul> `; Var data = {arr: [{name: "xiao Ming, age: 12, sex: 'f' hobbies: [" first", "the second"]}, {name: "little red", the age: 11, sex: 'm' hobbies: [" third ", "the fourth"]}, {name: 'small strong', age: 13, sex: 'f' hobbies: [" fifth ", "sixth "]},]} Mustache. Render (templateStr, data); console.log(domStr); let div = document.querySelector("div"); div.innerHTML = domStr; </script> </body>Copy the code

Boolean value

The < body > < div id = "list" > < / div > < script > var templateStr = ` {{# m}} < h6 > this can appear < / h6 > {{/ m}} `; var data = { m: true, } var domStr = Mustache.render(templateStr, data); console.log(domStr); let div = document.querySelector("div"); div.innerHTML = domStr; </script> </body>Copy the code

Mustache’s underlying core mechanism

The simplest implementation mechanism for a template engine is to use the replace() method in regular expressions. The second argument to replace() can be a function that takes an argument to the captured content, the $1 regular expression idea: By calling replace method, design {{}} as the target search object, that is, find a paragraph of content that begins with {{}, ends with}}, and is in the middle of the character, accurately capture the content in {{}}, replace with the attribute value of the corresponding attribute name in data. (This uses ES6’s new dynamic naming properties directly in object literals.)

The < body > < div class = "box" > < / div > < script > var templateStr = "< h3 > I think {{name}} {{appear}} < / h3 >"; Var data = {name: "Dao Zhi Jun you ", appear: } function render(templateStr, data) {return templateStr. Replace (/\{\{(\w+)\}\}/g, function (findStr, $1) { return data[$1]; // Equivalent to data. attribute name})}; let box = document.querySelector(".box"); var result = render(templateStr, data); console.log(result); box.innerHTML = result; </script> </body>Copy the code

But! When the template string is more complex, the expression is not enough, this time, you can use the idea of regularization to improve!

Bottom tokens

What is tokens?Tokens are nested arrays of JS (JS representations of template strings)

The mechanics of Mustache Mustache

Cyclic tokens: When loops exist in the template string, they will mutate into deeper nested tokens.

Mustache Low-level library focuses on accomplishing:

  • Mutate template strings into tokens;
  • Tokens are combined with data and parsed into DOM strings.

Here, I’ll devote another section to writing Mustache Library.