template engine

Template engine, the word “engine” has always made me feel tall and I want to comb it today.

To illustrate its usefulness, click the button to send an Ajax request for background server data, and then display the data in an empty table tag on the Web page

Node Small server implemented

var http = require('http')
var server = http.createServer()
server.on('request', function (req, res) {
    res.setHeader('Access-Control-Allow-Origin','*') //Cross domain resource sharing allows any source request.

    //jsonArray to simulate database data
    var data = `[{
        "name": "MicKong",
        "age": "20",
        "sex":"male",
        "tel":"123456",
        "address":"Beijing"
    },
    {
        "name": "May",
        "age": "18",
        "sex":"female",
        "tel":"123456",
        "address":"Hong Kong"
    }]`
    res.end(data)  //Responding to data data
})

server.listen(3000, function () {
    console.log('Server running...')
})

 

html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<table id="list"></table> <!--Displaying data in this empty table tag-->
<input type="button" id="btn" value="Getting data ">
<script>
    document.getElementById('btn').onclick = function () {
        var xhr = new XMLHttpRequest()
        xhr.open('get', 'http://127.0.0.1:3000')
        xhr.send()
        xhr.onreadystatechange = function () {
            var xhr = new XMLHttpRequest()
            xhr.open('get', 'http://127.0.0.1:3000')
            xhr.send()
            xhr.onreadystatechange = function () {
                if (xhr.readyState !== 4) return
                console.log(JSON.parse(xhr.responseText)); //First output to the console to see if the data has been successfully obtained.
            }
        }
    }
</script>
</body>
</html>

Browser successfully got data

 

The following data is not exported to the console, but is displayed directly to the current web page through DOM operation.

xhr.onreadystatechange = function () {
    if (xhr.readyState !== 4) return
    var data = JSON.parse(xhr.responseText);
    var table = document.getElementById('list')
    for (var i = 0; i < data.length; i++) {
        var tr = document.createElement('tr')
        var td1 = document.createElement('td')
        td1.innerHTML = data[i].name
        tr.appendChild(td1)

        var td2 = document.createElement('td')
        td2.innerHTML = data[i].age
        tr.appendChild(td2)

        var td3 = document.createElement('td')
        td3.innerHTML = data[i].sex
        tr.appendChild(td3)
        /* A little...*/
        table.appendChild(tr)
    }
    document.body.appendChild(table)
}

DOM Create rows and recreate columns, add columns to rows, add rows to tables… you can see the rendering of the data is very largeTedious,Not to mention when there’s a lot of data, you can use for… in and tr. innerHTML = ‘& lt; TD & gt; & lt; / TD & gt;’but it’s not easy enough.We can use template engine to render data.

 

The template engine is actually a API.String parsing replacement。Template engines come in many ways, much the same way, to make it easier to render data into HTML

Use hereart-template Template engine can be downloaded in GitHub or downloaded by NPM.

The command will be downloaded to the current directory, followed by the node_modules folder, node_modules/art-template/lib/template-web.js

node_modules Don’t change the folder.

 

Use steps

❶ After downloading script LabelIntroducing template engine into HTML

❷ Prepare a template.

❸ Prepare a data

❹ The template and data are integrated to get the rendering result HTML through a function provided by the template engine.

❺ Set the HTML of the rendering result to the innerHTML of the default element.

 

Introduce template-web.js and prepare a template to create a template based on the syntax in the template-web.js document

  

<script src="template-web.js"></script> <!-- Introducing template-web.js-->
<script id="temp" type="text/x-template-web"> <!--eachThe internal $value gets the elements that are currently traversed.-->
{{each target}}
<tr>
    <td>{{ $value.name }}</td>
    <td>{{ $value.age }}</td>
    <td>{{ $value.sex }}</td>
    <td>{{ $value.tel }}</td>
    <td>{{ $value.address }}</td>
</tr>
{{/each}}
</script>

Templates can be placed as strings in js, in table tags, or even divs, and so onscriptLabelIt’s because of the script tag.type If not, “text/javascript ” It will not be executed as JS code. The content in the tag will not only be displayed in new lines and colors, but also will not be displayed in the web page. It is a good place for template storage. The type value is as long as it is not “text/javascript”.xIt’s customized, followed by the name of the template engine used, so it’s written for the sake of fame

 

Prepare the data, integrate the template and data with the template engine API, and assign the result to the innerHTML of the element you want to render

template( ‘ scriptLabel ID ‘, {object}

xhr.onreadystatechange = function () {
    if (xhr.readyState !== 4) return
    var data = JSON.parse(xhr.responseText)

    //Template required data
    var content = {target: data} //targetThe name is optional, but it should be consistent with the each loop in the template.
    //Rendering data with API of template engine
    var result = template('temp', content) //The template and data are integrated to get the rendering result HTML through a function provided by the template engine.
    document.getElementById('list').innerHTML = result //Set the HTML of the rendering result to the innerHTML of table.
}

Click on the button, AJAX get the data, and use art-template to successfully render the data to the web page.

 

The template engine cares only about the template markup grammar that it knows.

as{{ }} ,Other contents will not be changed.

<script id="temp" type="text/x-template-web">
    Hello everyone, my name is "name".This year is ageLike {{each hobby}} + $value/each}}
</script>
<script>
    //templateFunction into templates and data
    var result = template('temp', {
        name: 'Paul',
        age: 20,
        hobby: ['fruits','songs','sports']
    })
    console.log(result)
</script>

 

Node Using template engine

The template engine was first born in the server domain, and then developed to the front end.art-template It’s ajstemplate engine,It can be used not only in browsers, but also in Node.

❶ Install NPM install art-template.npmAfter installation, you can use require () to load the code.

❷ Load art-template in the file module that needs to be used.

❸ Search the document, using the API of the template engine

 

   

template.render ( ‘ Template string, {object}

var template = require('art-template')

var result = template.render('hello {{ name }}',{
    name:'Paul'
})

console.log(result)

 

Next, we need to write template syntax in HTML (that is to say that the whole html is the upper part of the template.‘ Template string ),After rendering the server, respond to the browser.

demo.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>{{ title }}</title>
</head>
<body>
<h3>{{ title }}</h3>
<ul>
    <li>Name: name</li>
    <li>Age: + age</li>
    <li>Hobbies: {{each hobby}} + $value {{/each}}</li>
</ul>

<script>
    var str = '{{ title }}' //In the character string, the template engine can still recognize
</script>
</body>
</html>

 

The demo. HTML file is read in the background, and the template and data are integrated and returned to the browser through the render () method of the template module

var http = require('http') //httpModule creation server
var template = require('art-template') //Load art-template module
var fs = require('fs') //Load the FS module in order to read the file.
var server = http.createServer()
server.on('request', function (req, res) {
    fs.readFile('./demo.html',function (err,data) {
        if(err)
            return res.end('Can not find demo.html')
        //The content of the read file is binary, but render wants the string.
        var result = template.render(data.toString(),{
            name:'Paul',
            age: 20,
            hobby:['songs','sports','food'],
            title:'Personal information '
        })
        res.end(result)
    })
})

server.listen(3000, function () {
    console.log('Server running...')
})

Browser access, directly to the rendering results.

If it is rendered after the client asynchronous request, right-click to see the source code can not find the relevant content, if it is found in the page source code is rendered on the server side.

Client rendering is not conducive to SEO search engine optimization but user-friendly, service-side rendering can be crawled, client-side asynchronous rendering is difficult to crawl, so the real site is a combination of the two to do.

Leave a Reply

Your email address will not be published. Required fields are marked *