1. Why use a template engine

Why use a template engine in NodeJS. First of all, let’s imagine a scenario where the front end requests a set of data to the back end, and we want to render dom. In the past, the common operation was to use JS to join strings. Although this can solve the problem, it undoubtedly increases the readability and reduces the maintainability of the code. There’s nothing we can do if the requirements change.

There are many template engines to choose from within the Express framework. Ejs, PUG \ Jade, etc.

2. Introduction of PUG

In fact, pug is Jade. Jade was renamed pug. Let’s take a look at the basic syntax of PUG and its use in the Express framework.

Pug is a high-performance templating engine heavily influenced by Ham, implemented in JavaScript and available for Node. Through a set of syntax to a static section of the template, through the template engine will be dynamic data replacement, and then the generated HTML to the browser to parse and shading.

2.1 Characteristics of PUG:

1. Super readability

2. Client support

3. Flexible and easy-to-use indentation

4. Security, default code is escaped

5. Command line to compile jade template

6. Template inheritance

7. Chunk extension

8. Compilation and runtime context error reporting

9. HTML 5 model

10. Optional memory cache

11. Associate dynamic static tag classes

12. Parse tree processing using filters

13. Labels without prefixes

14. Native support for express modules

2.2 Installing puG

To use PUG, you need to install it globally.

NPM I pug -g// Global installation NPM I pug-cli -g// Global installation scaffoldingCopy the code

When using puG in a project, a partial installation is also required.

NPM init // Install package.json NPM I pug --save-dev // Partial installationCopy the code

compile

Pug pug file name -o Destination path -p -wCopy the code

Vscode can be compiled by installing plug-ins (not suitable for use in projects) :

Sass/Less/Stylus / / Jade/Typescript relation/Javascript Compile Hero Prowscats. Eno preview

3. Grammar relation

Basic skeleton:

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 =1.0") title Document bodyCopy the code

3.1 Tag Syntax

Each level of labels uses an extra indentation to indicate the nesting relationship, without closing labels or Angle brackets.

H1 This is a puG template example div UL Li SPAN P inputCopy the code

The li element in the above code has one more indent than the UL element, indicating that UL has a nested LI tag.

3.2 attributes

  1. Tag attributes look similar to HTML, but their values are just plain JavaScript.
div(class="box") this is a div elelement
Copy the code
  1. Run javascript variables directly
- var bool = true div(class=bool?" True ":"false") // Ternary operationCopy the code
  1. When there are many attributes, the display can be wrapped.
- var bool = true div(class=bool?" True ":"false") // Ternary operationCopy the code
  1. Boolean property (default true).
input(type='checkbox', checked)
Copy the code
  1. Style properties (which can be strings or objects).
p(style="color:#999999; font-size:18px") h2(style={color:"#666666","font-size":"20px"})Copy the code
  1. Class properties (which can be strings, like normal properties, or arrays).
div.foo
div.foo.bar
div(class="foo bar")
-var classes = ['box1','box2','box3']
div(class=classes)
div.bing(class=classes)
Copy the code
  1. The id attribute.
Div #box1 div(id="box2") // Since div is a common choice for tags, it can be omitted and is the default for tags. Oh #no #foo.oh.noCopy the code

3.3 the text

To output text is as simple as adding it after the element.

H1 This is an H1 tag. Box Hello pugCopy the code

Dynamic output content:

- var obj = {name:'tom'} 
p #{obj.name} is a man 
Copy the code

Output attribute values:

-var url = 'http://www.baidu.com' (href=urlCopy the code

3.4 PUG conditional statements

Pug supports pure native javascript, so conditional statements can also be supported.

- var flag = true 
if flag 
 p= flag 
else 
 p= flag 
Copy the code

3.5 PUG Loop statements

Pug provides two main methods for iteration, each and while, although the for loop can still be used.

For:

-var arr = [1,2,3,4,5] ul - for(var I =0; i<arr.length; i++) li= arr[i]Copy the code

Each:

- var arr = {name:'binge',six:'man'} 
ul 
 each val in arr 
 li= val 
Copy the code

While:

ul 
 while num<5 
 li= num++ 
Copy the code

3.6 a mixin hybrid

Equivalent to a function, can pass parameters

Skeleton:

//- define function mixin study //- code block p good good study //- function call + studyCopy the code

Example:

Mixin show(time) h3= time //- Check whether there is a block if block block else p no show +show('2017-11-11') p Singing and dancing //blockCopy the code

3.7 Template Inheritance

3.7.1 Support block and extends to inherit templates in PUG

Reuse of blocks of code often occurs in projects. Such as the head section of an HTML document. So we can pull it out as a common module.

Example:

common.pug

Doctype HTML HTML head title PUG template body H1 PUG template //- Which file inherits, calls which file block is content module Block ContentCopy the code

Index. Using the relation:

// extends extends syntax, common, extends common Block Content mixin show(name,... Shows) p=name ul each show in shows li= show +show('binge',' sing ',' dance ',' sleep ')Copy the code

Generated HMTL file:

<! DOCTYPE HTML > < HTML > < head > < title > relation template < / title > < / head > < body > < h1 > relation template < / h1 > < p > binge < / p > < ul > < li > singing < / li > < li > dancing < / li > <li> sleep </li> </ul> </body> </ HTML >Copy the code

3.7.2 contains

Pug allows you to insert the contents of another file into a file.

common.js

Pug include header Body H1 Pug template Block ContentCopy the code

header.pug

Title Pug Template Meta (charset=" utF-8 ")Copy the code

Generate HTML:

<! DOCTYPE HTML > < HTML > <head> <title>pug </title> <meta charset=" UTF-8 "> </head> <body> <h1>pug </h1> </body> </ HTML >Copy the code

4. Express rendering

Using PUG/JADE in Express is actually quite easy.

I’m using generators here to generate the Express MVC architecture.

Usage (Creating a routing file) :

var express = require('express');
var router = express.Router();

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});
router.get('/index',(req,res,next)=>{
  res.render('test');
})

module.exports = router;

Copy the code

As for the implementation, look at the implementation of the Express architecture.

This is common use:

var express = require('express'); var app = express(); var bodyParser = require('body-parser'); app.set('views','./views'); App.set ('view engine','jade'); Use (bodyParser.urlencoded({extended: true})); // Set app.use(bodyParser.urlencoded({extended: true})); // Application /x-www-formurlencoded app.get('/',function(req,res){res.render('jade',{title:'index page', function(req,res){function('jade',{title:'index page',); user:{ username:'tom', Password :123456}})}) app.listen(8888,function(){console.log('project running at http://127.0.0.1:8888')})Copy the code