5, Art template template engine

Statement: the correctness of personal study notes cannot be guaranteed

1. Basic concepts of template engine

1.) template engine

The template engine is a third-party module.
Let developers splice strings in a more friendly way, making the project code clearer and easier to maintain. For example:

// Writing without template engine
var ary = [{ name: 'Zhang San', age: 20 }];
var str = '<ul>';
for (var i = 0; i < ary.length; i++) {
str += '<li>\
<span>'+ ary[i].name +'</span>\
<span>'+ ary[i].age +'</span>\
</li>';
}
str += '</ul>';
<!-- Writing using template engine -->
<ul>
{{each ary}}
<li>{{$value.name}}</li>
<li>{{$value.age}}</li>
{{/each}}
</ul>


2.) art template template engine

Official website

Basic steps:

  1. Use the NPM install art template command in the command line tool to download
  2. Use const template = require ('art template ') to introduce the template engine
  3. Tell the template engine the data to be spliced and where the template is const html = template('template path ', data);
  4. Use template syntax to tell the template engine how to splice templates and data

By default, art files are not treated as html files in vscode, which requires additional settings: Reference blog

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
</head>
<body>
	{{ name }}
	{{ age }}
</body>
</html>
//The art template template is introduced to actually return a method
const template = require('art-template');
const path = require('path');
const views = path.join(__dirname, 'views', '01.art');
/*
template(Parameter 1, parameter 2)
Parameter 1: art template file path (absolute path is preferred)
Parameter 2: data used by art template file, object type
 Return art template file string (html)
*/
const html = template(views, {
    name: 'Zhang San',
    age: 20,
})
console.log(html);

Operation results:

PS D:\...\template> node app.js
<!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>Document</title>
</head>
<body>
    Zhang San 20
</body>
</html>


2. Syntax of template engine

Art template supports two kinds of template syntax at the same time: standard syntax and original syntax.
The standard syntax can make the template easier to read and write, and the original syntax has strong logical processing ability.


1.) output

Output some data in the template. The standard syntax and original syntax are as follows:

  • Standard syntax: {data}}
  • Original syntax: <% = Data% >
<!-- Standard grammar -->
<h2>{{value}}</h2>
<h2>{{a ? b : c}}</h2>
<h2>{{a + b}}</h2>
<!-- Primitive grammar -->
<h2><%= value %></h2>
<h2><%= a ? b : c %></h2>
<h2><%= a + b %></h2>

2.) original output

If HTML tags are carried in the data, the default template engine will not parse the tags, but will escape them and output them.
Standard original output syntax: {{@ data}}
Original text output syntax: <% - Data% >

<!-- Standard grammar -->
<h2>{{@ value }}</h2>
<!-- Primitive grammar -->
<h2><%- value %></h2>

3.) condition judgment

<!-- Standard grammar -->
{{if condition}} ... {{/if}}
{{if Condition 1}} ... {{else if Condition 2}} ... {{/if}}
<!-- Primitive grammar -->
<% if (Condition 1) { %> 
... 
<% } else if (Condition 2) { %>
... 
<% } else { %>
...
<% } %>

Note: native js syntax is supported inside the original syntax output

4.) cycle

Standard syntax: {each data}} {{/each}}
Original syntax: <% for() {% >... <%}% >

<!-- Standard grammar
each: Template cycle identifier
target: Data to cycle
$index: Index of the current circular item
$value: The value of the current loop item
-->
{{each target}}
{{$index}} {{$value}}
{{/each}}
<!-- Primitive grammar
 Primordial js grammar
-->
<% for(var i = 0; i < target.length; i++){ %>
<%= i %> <%= target[i] %>
<% } %>

5.) sub template

The sub template can be used to extract the public blocks of the website (such as the header and bottom label blocks) into a separate file.
The child template (public template) is introduced into other templates by using include

  • Standard syntax: {{include 'child template relative path'}}, where include represents an identifier
  • Original syntax: <% include ('sub template relative path template ')% >, where include represents a method
<!-- Standard grammar -->
{{include './header.art'}}
<!-- Primitive grammar -->
<% include('./header.art') %>

6.) template inheritance

Template inheritance means that other templates can inherit some public templates, similar to sub templates, but template inheritance can be used to extract the website HTML skeleton into a separate file, and other page templates can inherit the skeleton file.

Syntax:
In other templates, use {{extensions' relative path of inherited template '}} to inherit the public template

Template inheritance can specify some parts of the inherited template according to the needs of the current template

  • In the inherited template, use {{block 'reserved empty name'} {/ block}} to set the reserved empty name
  • In other templates, use {{block 'reserved empty name'}} to specify content {{/ block}} to fill the reserved hole

Simple case:

<!-- Common skeleton template layout.art -->
<!doctype html>
<html>
	<head>
		<meta charset="utf-8">
		{{block 'title'}}{{/block}}
		{{block 'link'}}{{/block}}
</head>
<body>
{{block 'content'}}{{/block}}
</body>
</html>
<!--index.art Home page template-->
{{extend './layout.art'}}
{{block 'title'}} <title>This is the home page</title> {{/block}}
{{block 'link'}} <link rel="stylesheet" href="custom.css"> {{/block}}
{{block 'content'}} <p>This is just an awesome page.</p> {{/block}}

Command line output

PS D:\...\template> node 05.js
<!doctype html>
<html>
        <head>
                <meta charset="utf-8">
                 <title>This is the home page</title>
                 <link rel="stylesheet" href="custom.css">
</head>
<body>
 <p>This is just an awesome page.</p>
</body>
</html>
PS D:\...\test\template>

7.) template configuration

Import variables into the template

/*
template: The art template template engine module imported from the current js file
*/
template.defaults.imports.Variable name = Variable value;

After the statement is executed, the variable can be used in the linked template

dateformat

Usage scenario: format date data in template
Reference to third-party modules: dateformat - npm

{{dateformat(time, 'yyyy-mm-dd')}}
const template = require('art-template');
const path = require('path');
const dateformat = require('dateformat');
const view = path.join(__dirname, 'views', '06.art');

//!  Import template variables
template.defaults.imports.dateformat = dateformat;
const html = template(view , {
    time: new Date(),
});
console.log(html);

Command line output

PS D:\...\template> node 06.js
2021-09-01

Set template root directory

Render multiple templates through multiple templates (), but you have to manually set the template address each time

const view1 = path.join(__dirname, 'view', '01.art');
const view2 = path.join(__dirname, 'view', '02.art');
console.log(template(view1,{}));
console.log(template(view2,{}));

This will cause code redundancy

By setting the template root directory, you only need to specify the template file name every time you call template() to render the template, and let the template engine automatically find the specified template file in the template root directory

/*Set the root directory of the template
template: The art template template engine module imported from the current js file
*/
template.defaults.root = path.join(__dirname, Root directory name);

Simple case

const template = require('art-template');
// Set the root directory of the template
template.defaults.root = path.join(__dirname, 'views');
console.log(template('06.art', {
	msg: '06.art The template file is automatically found and rendered'
}))

Set template default suffix

By setting the default suffix of the template:

// Configure the default suffix of the template
//Template: the art template template template engine module imported from the current js file
template.defaults.extname = '.html';

Specify the template file name directly when template() renders the template (no suffix is required):

console.log(template('07', {
	msg: 'The template engine automatically finds the template in the root directory "07.html" Template file and render'
}));

Of course, if the full name of the template file (including the suffix) is specified, the template engine will automatically go to the root directory to find the specified file and render.


Keywords: Javascript node.js html

Added by coder4Ever on Sun, 19 Dec 2021 21:32:38 +0200