Hello everyone, I am a sophomore student, front-end enthusiast. This is my first article with the Nuggets. Share my study notes. More will be shared in the future. Hope to pay attention to oh!

This is a study note of the template engine, here are some simple examples of use and a brief introduction to the principle. If there is something wrong, please point it out. Thanks for reading!

You can also follow my blog, where I share some of my study notes and some knowledge here and here!

A template engine

What is a template engine

Official explanation: “A template engine (specifically a template engine for Web development) is designed to separate the user interface from the business data (content). It can generate documents in a specific format. A template engine for a Web site produces a standard HTML document.”

Look not to understand

To put it simply, separate the business logic layer from the display layer, combine the data with the template through the engine, and then display the results.

Take a chestnut

You need to write an article reply page, reply block code has many places to fill in the data (such as: reply person’s information, reply person’s ID, reply content, reply liked number…..)

Before ES5, the usual approach was to concatenate code with data through string concatenation and then add it to a node.

SomeNode.innerHTML = '<div>'+data1 + '<text>'+data2 + ........ +'</div>'
Copy the code

But a lot of tag strings and data concatenation is ugly, and it’s hard to see its structure quickly. And difficult to maintain. Once the structure is complex, the more variable data need to be spliced, the more difficult it is to operate

ES6 gives us template strings that allow line breaks, variable insertions, functions, etc. It’s convenient for us a lot

 SomeNode.innerHTML = ` 
      
// lot of code ....
`
Copy the code

The structure is clear and much clearer, but when the structure is complex and there is a lot of data, the code can also become bloated and ugly, like having to insert some data of the same structure in a loop. We have to create a method specifically to handle it or use another method

This is where the template engine comes in

Use of template engines

1. Introduction of the template engine

The recommended one is art-template

Go to the official website here

Go to the downloadable art-template package, import it with the script tag, or install it with Node.js

  • To introduce via the script tag:<script src="template-web.js"></script> Start by downloading the code locally template-web.js
  • Install via NPM:npm install art-template --save

2. Customize a template

2.1 Write codes according to requirements

To define a template with the script tag, you need to define an ID for the template. The ID is used to associate data with the template

The type attribute cannot be empty, nor can it be a JS class. It can be written as text/ HTML, which looks nicer with HTML highlights

    <script type="text/html"  id = "Tem"> // The ID must be in the script tag
        <ul class = "person">	
            <li>Name:</li>
            <li>Skills:</li>
            <li>Hobbies:</li>
        </ul>
    </script>
Copy the code
2.2 Reserved Position

Use two curly braces to reserve a space where you want to populate the data, and give the space a name and place it in two brackets

<script type="text/ HTML "id =" Tem"> <ul class =" person"> <li> name: {{name}} {{habbit}} </li> </ul> </script>Copy the code
2.3 Creating or retrieving data objects through Ajax
2.4 Call the template() method of the template engine to populate the data
<script>	
	  // Create your own data
       var data = {
            name: 'ha ha'.// Note that the property name must be the same as the name of the reserved location
            skill: 'laugh'.habbit: 'like a Cheshire cat'
       }
	  // Call the template method
      // The template method associates data with a template, populates it, and returns comments within the template
	 var res = template("Tem", data)	Parameter 1: indicates the template ID. Parameter 2: indicates the filled data
     // In this case, res is the populated data
</script>
Copy the code
Note:

Either the template defined or the data returned after filling is a string, which can be converted to a node object and appen, or added to the target node using innerHTML

The target engine’s data filling process does not escape the data. It is interpreted as the innerText filling. If the data is a label, the @ sign must be preceded by the name of the reserved position

<div>{{@urlA}}</div>
<! - data for urlA = "< a href =" www.baidu.com "> baidu < / a >" -- >
Copy the code

Target engine other functions

1. The logic of the if

** Use the {{if key === value}} template (all or part) {{/if}} **

If the statement after If is true, the template block inside the If is filled in, and then returned, If not false is not filled in

**If can be followed by else If,else **

{{if name ==' hee hee '}}<! -- check if the name of the passed data is equal to 'hee hee, fill the template block in if for true' -->
 <li>Name: {{name}}</li>
 <li>Height: {{skill}}</li>
 <li>Age: {{habbit}}</li>
 {{/if}} 					<! -- Always end with -->{{else name == "ha ha "}}<li>Name: {{name}}</li>
 <li>Weight: {{weight}}</li>
 <li>Gender: {{gender}}</li>
 {{/else}}				<! -- Always end with -->
Copy the code

2. Each loop

Using the template engine’s each loop, you can iterate over a template block without having to write the same template block many times and dynamically populate it

Add data as follows:

        var person = {
            name: 'big baby'.bro: [
                'two dolls'.'three dolls'.'four Eva'].family:[
              {  name:'grandfather'.skill:'caught'},
              {
                  name:'pangolin'.skill:'what'}}]Copy the code
Use each’s template

With {{each data}} template block {{/each}}

 <script type="text/html" id='forTem'>
      <ul>
          <li>{{name}}</li>
          <li>Younger brothers<ul>
                  <! -- loop statement, subscript -->
                  <! -- <li>{{bro[0]}} 
  • {{bro[1]}}
  • {{bro[2]}}</li> --> <! -- each loop --> {{each bro}} <! -- each loop tag, put the loop data after --> <li>{{$index}} {{$value}}</li> <! --{{$index}}The index{{$value}}Value - > {{/each}} <! -- each tag must end with --> </ul> </li> <li>family<ul> {{each family} <li>{{$value.name}}----{{$value.skill}}</li> <! [] method can be used to retrieve properties of array objects. {{/each}} </ul> </li> </ul>
    </script> Copy the code

    The template engine is based on simple simulation

    Basic principle: in fact, the template is defined through a special method. After obtaining the template, a regular expression obtains the location of the data to be filled, and finally returns the data.

    Simple simulation:

    // function myTem(id, Data) {var Tem = document.querySelector("#"+id).innerhtml var reg = /{{(\w+)}}/; Var res = reg.exec(Tem) // return null, while (res) {// if there are multiple padding bits of the same name, Replace (res[0], Data [res[1]]) // retrieve res = reg.exec(Tem)} return Tem} // import and use // <script SRC ="./my-tem.js"></script> // <script> // / <script> // var data = { // 'name': 'fupo', // 'skill': 'rich' // } // myTem(ID,data) // </script>Copy the code