1. Use art-template in nodejs

1.1 installation art – the template

 npm install art-template --save
Copy the code

1.2 Load the Art-template in the required file module

var template = require('art-template')
Copy the code

1.3 the use of

/** * Use art-template */ in nodejs

var fs = require('fs')
// Introduce the third-party art-template module
var template = require('art-template') 

// Read the index.html template file
fs.readFile('./index.html'.function(err, data) {
    /** * data reads binary data by default, whereas the template engine's render method needs to receive a string, so we need to convert the binary data to a string */
    if (err) {
        return console.log('File reading failed')}var ret = template.render(data.toString(), {
        name: 'Li Siyu'.age: 18.province: 'Beijing'.hobbies: [
            'Write code'.'singing'.'Play games'].title: 'Personal Information'
    })
    console.log(ret)
})
Copy the code

Index.html template file

<! DOCTYPEhtml>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
    <title>Use art-template in nodeJS</title>
</head>

<body>
    <h1>This is my {{title}}</h1>
    <h3>Hello everyone, my name is {{name}}</h3>
    <h3>I am {{age}} years old</h3>
    <h3>I'm in {{province}} now</h3>
    <h3>{{each hobbies}} {{$value}} {{/each}}</h3>
</body>

</html>
Copy the code

2. Use art-template in the browser

Template-web. js: import third-party files

<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta Name ="viewport" content="width=device-width, initial-scale=1.0"> <title> Use art-template</title> </head> <body> <! - 1. The introduction of art - the template. Js - > < script SRC = ".. / template - web. Js "> < / script > <! -- 2. Define the template --> <! The template engine does not care about the contents of your string, only the syntax of the template markup that it knows, such as {{}} in <script id="tpl-user" type="text/ HTML ">, whatever it is, <script id="tpl-user" type="text/ HTML "> {{name}} < / p > < p > I {{age}}, < / p > < h1 > I am from {{province}} < / h1 > < p > my hobbies are: {{each hobbies}} {{ $value }} {{/each}}</p> </script> <! <script type="text/javascript"> var user = template('tpl-user', {name: 'li Siyu1 ', age: 20, type: 1) 'Beijing' hobbies: [' writing code ', 'sing', 'game']}) console. The log (user) < / script > < / body > < / HTML >Copy the code

3. Express-art-template for NodeJS with Express

3.1 Downloading the Installation Package

npm install --save express
npm install --save art-template
npm install --save express-art-template
Copy the code

3.2 Importing and Creating an HTTP server

var path = require('path')
var express = require('express')
var app = express()
Copy the code

3.3 Specify the parsing engine to use for.html.

app.engine('html'.require('express-art-template'))
Copy the code

3.4 Using a Template to Transfer Values

// Request and response
app.get('/'.function(req, res) {
    // Use templates to pass values
    res.render('index.html', {
        name: 'Li Siyu'.age: 18.province: 'Beijing'.hobbies: [
            'Write code'.'singing'.'Play games'].title: 'Personal Information'
    });
});

Copy the code

3.5 Case Presentation

/ WWW /index.html template file

<! DOCTYPEhtml>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
    <title>Use art-template with Express in NodeJS</title>
</head>

<body>
    <h1>This is my {{title}}</h1>
    <h3>Hello everyone, my name is {{name}}</h3>
    <h3>I am {{age}} years old</h3>
    <h3>I'm in {{province}} now</h3>
    <h3>{{each hobbies}} {{$value}} {{/each}}</h3>
</body>

</html>

Copy the code

app.js

var path = require('path')
var express = require('express')

// Create web server
var app = express()

// Specify the parsing engine to use for.html, which means that the art-template template engine will be used when rendering.html files
app.engine('html'.require('express-art-template'))

// Express-art-template default render directory is under views, if you need to modify, set as follows:
app.set('views', path.join(__dirname, 'www')); // The WWW directory is where the template HTML is placed

// 4. You can directly access all resources in the public directory through /public/xx
// When it starts with /public/, go to the./public/ directory to find the corresponding resource
app.use('/public/', express.static('./public/'))

// Request and response
app.get('/'.function(req, res) {
    // Use templates to pass values
    res.render('index.html', {
        name: 'Li Siyu'.age: 18.province: 'Beijing'.hobbies: [
            'Write code'.'singing'.'Play games'].title: 'Personal Information'
    });
});
app.listen(3000.function() {
    console.log('server is running ...... ')})Copy the code

3.6 analytical

3.6.1 Loading parsing template engine Art-template, which needs to be used with render

// Express provides a method for the Response corresponding object: render
The render method is disabled by default, but can be used if a template engine is configured
// res.render(' HTML template name ', {template data})

render("File name",{template data})Copy the code

Note: the first parameter cannot be written to the path. By default, you will go to the views folder in your project to find the template file. This is the Express convention

3.6.2 Configuring a Template Engine Name extension

app.engine('html'.require('express-art-template'));
Copy the code

The first parameter indicates that the template engine file suffix will be used, which is art by default, and in our project we will use HTML

3.6.3 Modifying the Default Template File Directory

app.set('views', path.join(__dirname, 'www')); // The WWW directory is where the template HTML is placed__dirname: Is the directory in which you execute the node app.js projectCopy the code

Express-art-template default render directory is under views, if modified, refer to above

Art-template uses template inheritance and subtemplate cases

4.1 Project Initialization

npm init -y
Copy the code

4.2 Installing project packages

#Install the Express service framework package
npm i express

#Install art-template and Express-art-template
npm i art-template express-art-template

Copy the code

4.3 Other documents of the project

app.js

var express = require('express')
var path = require('path')

// Create web server
var app = express()

// Open the website to unify static resources
app.use('/public/', express.static(path.join(__dirname, './public')))
app.use('/node_modules/', express.static(path.join(__dirname, './node_modules')))

// Configure the art-template template engine
app.engine('html'.require('express-art-template'))
// The express-art-template default render directory is views
app.set('views', path.join(__dirname, './views'));

app.get('/'.function(req, res) {
	res.render('index.html', {
		name: 'hello nodejs'
	})
})

app.listen(3000.function() {
	console.log('Server is runing at http://localhost:3000/')})Copy the code

Views directory file

header.html

<link rel="stylesheet" type="text/css" href="/public/css/header.css" />
<header class="section_header">
	<h1>Public head</h1>
</header>

Copy the code

footer.html

<link rel="stylesheet" type="text/css" href="/public/css/footer.css" />
<footer class="section_footer">
	<h1>Public tail</h1>
</footer>

Copy the code

index.html

<! -- 1. Inherit template layout.html -->
{{extend './layout.html'}}

<! -- 2. Set the title of the custom module -->
{{block 'title'}}
<title>Home page</title>
{{/block}}

<! -- 2. Set custom module head -->
{{block 'head'}}
<link rel="stylesheet" type="text/css" href="/public/css/index.css" />
{{/block}}

<! -- 2. Set custom module cont -->
{{block 'cont'}}
<h1 class="title">{{name}}</h1>
{{/block}}

Copy the code

layout.html

<! DOCTYPEhtml>
<html>
	<head>
		<meta charset="utf-8" />
		<meta name="viewport" content="width=device-width, initial-scale=1">
		{{block 'title'}}
		<title>Art-template template inheritance and child templates</title>
		{{/block}}
		<link rel="stylesheet" type="text/css" href="/public/css/reset.css" />
		<link rel="stylesheet" type="text/css" href="/public/css/general.css" />
		{{block 'head'}}{{/block}}
	</head>
	<body>
		<! -- Introduce common headers -- subtemplate -->
		{{include './header.html'}}
		
		<article class="section_container">
			{{block 'cont'}}{{/block}}
		</article>
		
		<! -- Introducing a common tail -- subtemplate -->
		{{include './footer.html'}}
	</body>
</html>


Copy the code