当前位置:网站首页>Node template engine (EJS, art template)

Node template engine (EJS, art template)

2022-04-23 17:14:00 MiMenge

template engine

1 ejs template engine

install ejs template engine

$ npm i ejs -s 

Using the template engine

const express = require('express');

const app = express();

//  Set the view template engine  'ejs'
app.set('view engine', 'ejs');

//  Configure template directory   Let the program go to the location of the template engine 
app.set('view', './views');

app.get('/show', (request, response) => {
    

	//  Rendered data 
    let persion = [{
    
        uname: 'TOM', age: 20
    }, {
    
        uname: 'ANDY', age: 22
    }, {
    
        uname: 'TONY', age: 46
    }, {
    
        uname: 'JERY', age: 18
    }];
    
	//  Return to page file 
    response.sendFile(`${
      __dirname}/public/index.html`);
    
    //  Render the page 
    response.render('engine', {
    data: ' Template engine data ', age: 22, persion, template: '<h1>hello ejs!</h1>'});
});


app.listen(4400, (err) => {
    
    if (!err) {
    
        console.log('ok');
    } else console.log(err);
});

views Under folder engine.ejs file

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>

<!--
    ejs grammar 
        1 < % js Code  % >> :  Can write arbitrary code , But it won't output anything in the browser 
        2 < %-  Variable  % > : Objects that can be passed from the back end key designated value Render to page ( Transferred )
        3 < %=  Variable  % > : Objects that can be passed from the back end key designated value Render to page ( Not transferred )
		···
-->

<p> This is a new page </p>
<p>
    <% console.log('@') %>
</p>

<% for (let k = 0; k < 10; k++) {
    console.log(k);
} %>

<p><%- data %>, <%= age %></p>

<!--
    < %- % > and < %= % > The difference between 
-->

<!-- Parsed html-->
<%- template %>

<!-- Unresolved html-->
<%= template %>


<!-- Circular rendering -->
<%
for(let o = 0; o < persion.length; o++ ){
%>
    <p> I am a <%= persion[o].uname %>, age<%= persion[o].age %></p>

<% }
%>

<!-- Be careful : This approach goes against the idea of separating the front and back ends , It will make it difficult to maintain later projects -->

</body>
</html>

Server printing

D:\Nodejs\node.exe D:\ project \ Front end cases \NODE.JS\ template engine \app.js
ok
@
0
1
2
3
4
5
6
7
8
9

2 art-template template engine

2-1 install

$ npm i art-template -s

2-2 Use

Introduce... Into the server file tempalte

const art = require('art-template');

2-3 Render to html

art.render(fileUrl, {
    data});

Parse rendering html
fileUrl: Analytic htm
{data}: Rendered data objects

example
app.js

const express = require('express');

const app = express();

//  Introduce template engine 
const art = require('art-template');

const fs = require('fs');

app.get('/show', (request, response) => {
    

    fs.readFile(`${
      __dirname}/public/index.html`, (err, data) => {
    
        if (err) {
    
            console.log(err);
            return;
        }

        //  Render the specified html file 
        let html = art.render(data.toString(), {
    
            name: 'TOM',
            age: 22,
            html: '<i>123456</i>',
            a: 20,
            b: 10,
            obj: {
    prop1: [1, 2, 3, 4]},
            bool: false
        });

        //  Will use render The rendered page returns 
        response.send(html);
    });

});

app.listen(4400, (err) => {
    
    if (!err) {
    
        console.log('ok');
    } else console.log(err);
});

html file

<!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>
<!-- This is a preliminary rendering using the template engine -->
<p>{
   {name}}</p>

<h1> Age is {
   {age}}</h1>

<!-- Unable to resolve html-->
{
   {html}}
<p>{
   {html}}</p>

//  have access to 
// {
   {@ }} Parsing html
{
   {@ html}}

<p>{
   {a + b}}</p>

<p>{
   {bool || obj['prop1']}}</p>

</body>

</html>

2-4 art-template grammar

{ {}} It is a module of template engine parsing , You can write variables or expressions

2-5 sentence

  • Variable
<!-- Variable -->
<!-- Defining variables -->
{
   {set tem = name}}
<!-- Using variables -->
<h1>{
   {tem}}</h1>

<!--TOM-->

  • Loop statement

{ {each target}}
{ {$ index}} { {value}}
{ {/ each}}

<!-- loop -->
{
   {each target=obj['prop1']}}
<p> The value is :{
   {$value}},index yes :{
   {$index}}</p>
{
   {/each}}

// The value is :1,index yes :0

 The value is :2,index yes :1

 The value is :3,index yes :2

 The value is :4,index yes :3

amount to forEach
${ {index}} ===> foreach Medium Index

${ {value}} ===> foreach Medium value

target It refers to the target object of traversal


  • Conditional statements

{ {if value}} … { {/if}}
{ {if v1}} … { {else if v2}} … { {/if}}

<!-- Judge -->
{
   {if bool===true}}
<p> really </p>
{
   {/if}}
<p> false </p>

{
   {if a + b > 10}}
<p> Greater than 10</p>
{
   {else if a + b === 10}}
<p> be equal to 10</p>
{
   {else}}
<p> Less than 10</p>
{
   {/if}}

<!--  false   Less than 10 -->

Be careful : Conditions written in if Back

2-5 Template inheritance

{ {extend ‘./layout.art’}}
{ {block ‘head’}} … { {/block}}

Template inheritance allows you to build a basic template that contains common elements of your site “ skeleton ”.

<!-- Template -->
<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <title>{
   {block 'title'}}My Site{
   {/block}}</title>
</head>
<body>
    {
   {block 'content'}}{
   {/block}}
</body>
</html>

<!--child.html-->
{
   {block 'content'}}
<p>This is just an awesome page.</p>
{
   {/block}}

Rendering index.html after , The layout skeleton is automatically applied .


2-6 Sub template

{ {include ‘./header.art’}}
{ {include ‘./header.art’ data}}

art-template The built-in HTML compressor , Please avoid writing HTML Abnormally closed sub templates , Otherwise, the label may be accidentally compressed after compression is turned on “ Optimize .


2-7 filter

Registration filter

template.defaults.imports.dateFormat = function(date, format){
    /*[code..]*/};
template.defaults.imports.timestamp = function(value){
    return value * 1000};

Register filter functions , Use the pipe symbol when using on , Pass the data into the filter function for corresponding operation

and vuejs The pipe symbol in is similar to

The first parameter of the filter function accepts the target value .

Standard grammar
{ {date | timestamp | dateFormat ‘yyyy-MM-dd hh:mm:ss’}}
{ {value | filter}} The filter syntax is similar to the pipe operator , Its last output is the next input .


2-8 To configure

file name template.defaults

//  Template name 
filename: null,

//  Template syntax rule list 
rules: [nativeRule, artRule],

//  Whether to enable the automatic coding function of template output statements . by  false  Then turn off the coding output function 
// escape  Can guard against  XSS  attack 
escape: true,

//  Start template engine debugging mode . If  true: {cache:false, minimize:false, compileDebug:true}
debug: detectNode ? process.env.NODE_ENV !== 'production' : false,

// bail  If  true, Both compilation errors and runtime errors throw exceptions 
bail: true,

//  Open cache or not 
cache: true,

//  Whether to turn on compression . It will run  htmlMinifier, Page  HTML、CSS、CSS  Compress the output 
//  If the template contains no closed  HTML  label , Please don't open  minimize, Otherwise it may be  htmlMinifier  Repair or filter 
minimize: true,

//  Whether to compile debug version 
compileDebug: false,

//  Template path converter 
resolveFilename: resolveFilename,

//  Sub template compilation adapter 
include: include,

// HTML  compressor . Only in  NodeJS  Effective in the environment 
htmlMinifier: htmlMinifier,

// HTML  Compressor configuration . See  https://github.com/kangax/html-minifier
htmlMinifierOptions: {
    collapseWhitespace: true,
    minifyCSS: true,
    minifyJS: true,
    //  Automatically merge at run time :rules.map(rule => rule.test)
    ignoreCustomFragments: []
},

//  Error events . Only in  bail  by  false  Effective when 
onerror: onerror,

//  Template file loader 
loader: loader,

//  Cache center adapter ( rely on  filename  Field )
caches: caches,

//  Template root directory . If  filename  Field is not a local path , It's in  root  Find template 
root: '/',

//  Default suffix . If there is no suffix , It will be added automatically  extname
extname: '.art',

//  Ignored variables . List of template variables ignored by the template compiler 
ignore: [],

//  Imported template variables 
imports: runtime

2-9 api

  • template(filename, content)
    Render the template according to the template name .

Parameters :

{string} filename
{Object,string} content

Return value :

If content by Object, Render the template and return string
If content by string, Then compile the template and return function

The browser version cannot load external files ,filename To store the elements of the template id


  • compile(source, options)
    Compile the template and return a rendering function .

Parameters :

{string} source
{Object} options

Return value :
{function}


  • render(file, data, options)
    Compile and return rendering results .

Parameters :

{file} Target render object
{data} The data on the noise
{Object} Configuration item

版权声明
本文为[MiMenge]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204230553027751.html