Use of template engine in NodeJS

A. Art – the template

Art-template is a high-performance JavaScript template engine that can be used not only in the browser (front end) but also in Node.

How it works: The art-template principle is to replace a string of data with certain formatting data according to the syntax of the template engine, and then produce the HTML document we need. Art-template supports two syntax types: standard syntax and primitive syntax. Standard syntax is usually {{}}, and primitive syntax is usually <% %>. There are details on the official website

** Usage: ** Refer to the documentation on the official website for detailed usage rules

Art-template Chinese document

2. The Demo

Next, we use the art-template template to render an HTML interface to the browser

1. Create a Demo folder and run the NPM init -y command to initialize the folder

2. Install the art-template template in the folder

npm install art-template -D
Copy the code

3. Create an HTML template

// index.html


      
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>{{ title }}</title>
</head>
<body>
    <h1>{{ title }}</h1>
    <p>My name is {{ name }}</p>
    <p>I come from {{ from }}</p>
    <p>I like {{each hobbies}} {{ $value }} {{ /each }}</p>
</body>
</html>
Copy the code

4. Create server, render template, load data

// server.js

const http = require('http')
const server = http.createServer()
const tempplate = require('art-template')
const fs = require('fs')

// Enable request listening for the server
server.on('request',(req,res)=>{
    if(req.url === '/'){
        fs.readFile('./index.html',(err,data)=>{
            if(err){
                return res.end('readFile failed... ')}const dataStr = data.toString()
            // Use art-template to load data into the template interface
            const strHtml = tempplate.render(dataStr,{
                title: 'Personal Introduction'.name: 'Kobe'.from: 'America'.hobbies: ['basketball'.'swimming'.'sleep']})// Return the loaded template string to the browser
            res.end(strHtml)
        })
    }else{
        res.end('err url... ')}})// Set the port number to listen on and the callback function to listen on
server.listen(3000, () = > {console.log('Server is running... ')})Copy the code

5. Start the server and enter the URL in the browser