concept
Template engines allow programs to separate interfaces from data, business code from logical code, which greatly improves development efficiency, and good design makes code reuse easier.
It's no use just looking at hard concepts. Let me explain in detail what this template engine is.
Suppose you now open your computer browser, enter a treasure's website, and then enter a "notebook", and a wide range of goods appear on the next page, making you overwhelmed with them, and then you enter a "hot strip", which makes a different product on the next page. The question arises: Are these items written directly on the page or rendered in real time?
Undoubtedly, the goods on display must be rendered in real time. If they are written to death directly on the page, we need a new page every time we enter different keywords to find them. This will result in too much memory to be used at all, which is not cost-effective, and the role of the template engine is reflected in this. It can render html pages in real time based on real-time data extracted from the database, which is the template engine.
Example
Here's an example
The image above is taken from the back-end database, you can see that the original data is not formatted, so before we render the data, we need to format the original data to get the data that can be directly rendered.
While formatting the data, we also set the default values for the part of the data that needs to be returned
Regular expressions are used here to remove the "PTD!6-" at the beginning of the productTitle in the original data.
productTitle = productTitle.replace(/PTD16-/gi, '');
The null value merge operator'?'is used here to set the default value
productTitle = productTitle ?? 'No information yet';
Null Value Merge Operator?? Provides a short syntax for getting the first "defined" variable in the list (Note: Value is not a null or undefined variable).
Let's write our own compilation template to generate rendering data
The template string for es6, also known as the inverted quotation mark ``, is used here, which can be used to stitch as a regular string and also to embed variables, as shown in the figure above
${item?.productImgUrl ?? 'No information yet'} ${item?.productTitle ?? 'No information yet'} ${item?.productDesc ?? 'No information yet'} ${item?.productPrice ?? 'No information yet'}
These four are the variables embedded in the string, then fill in the corresponding data through a loop, and finally, through this template of the li tag, you can generate this part of the html page from the data
Because we use object-oriented writing here, whether it's a formatting function, a compilation template function, or a member function of a class
All you need to do in the renderHtml function is render the page
renderHtml() {//Render Page this.parentEle.innerHTML += this.templateHtml; }
And don't forget to instantiate classes before these
new TempRender(productData, '#product-list');
html tag section, just one ul tag with id'product-list'
<body> <ul id="product-list"> </ul> <body>
The final rendered page is shown in the diagram
Although the rendering was successful at the end, we need to rewrite the template for different labels or different projects, which can be tedious, so we will use the template tools next. There are a lot of template tools on the market today. What we are using today is art-template
Template Engine Tool: art-template
Template tools are easy to use, so you can see how to use them by visiting the art-template website and checking the documentation
After introducing the corresponding js file into the file, we need to understand the syntax of the tool and view it in the document
Before we get to the syntax, let's see how we use the template engine in practice
let oUl = document.querySelector('#product-list'); let templateHtml = template('testTemp', formatData(productData)); oUl.innerHTML = templateHtml; function formatData(data) {//Format the original data and return the part of the data that needs to be rendered let list = data.list; data.list = list.map(({ productImgUrl, productTitle, productDesc, productPrice, productCount }) => { productPrice = productPrice / 100; productTitle = productTitle.replace(/PTD16-/gi, ''); productImgUrl = productImgUrl || 'img/1.webp'; productTitle = productTitle ?? 'No information yet'; productDesc = productDesc || 'No information yet'; productPrice = productPrice || 'No information yet'; return { productImgUrl, productTitle, productDesc, productPrice, productCount } }) return data; }
The original data here is the same as before, but instead of writing a compilation template, we call the template function directly. We pass in two parameters,'testTemp'and the processed data. The powerful template tool will return the compiled html part to us, and then we just need to render it on the page to see the effect.
Here's one thing: what's the parameter'testTemp', we found the label with id'testTemp'
Note here that the value of the script tag's type must be'text/template', which is the format specified by the template engine
As you can see, this tag says the grammar of the template. As for the grammar, let's look at the document again
Because the original grammar is too complex, we use the standard grammar
Standard syntax is easy to use. You can use {{}} to embed variables in the part of the data that needs to be rendered. You can also use special statements in templates, such as loops, if statements, etc., but we generally only use these statements to render data more easily, such as
{{set price = $value.productPrice}}
This type of programming statement is not suitable for appearing within a template
As we mentioned above, using the template function to pass in two parameters, the first is the type specified by the engine, the second is the processed data, which is a top-level variable in the template above, because the data is in the format of a JSON object, with one'title'and one'list', both of which can be used directly in {}
<h1>{{title}}</h1> {{each list}}
If you use the title variable directly and loop through the list variable, the value of each item in the loop can be expressed as'$value', so we can see that in the loop
Note:'$index'is the subscript for each item
{{each list}} <li> {{set price = $value.productPrice}} <img src="{{$value.productImgUrl}}" alt=""> <h3 class="title">{{$value.productTitle}} {{$index}}</h3> <p class="desc">{{$value.productDesc}}</p> <p class="price"><span>{{price}}</span>Yuan Qi</p> {{if $value.productCount == 0}} <i style="color:red">No Goods</i> {{/if}} {{if $value.productCount != 0}} <i style="color:green">In stock</i> {{/if}} </li> {{/each}}
Finally, the page rendered with the template engine is