[Nodejs] Express template use

insert image description here

1. Installation of Express Scaffolding

There are two ways to install Express scaffolding:

Install using express-generator

Use the command line to enter the project directory and execute in sequence:

cnpm i -g express-generator

The command meaning of the command line can be viewed through express -h

express -h

Usage: express [options] [dir]

Options:
    --version        输出版本号
-e, --ejs            添加对 ejs 模板引擎的支持
    --pug            添加对 pug 模板引擎的支持
    --hbs            添加对 handlebars 模板引擎的支持
-H, --hogan          添加对 hogan.js 模板引擎的支持
-v, --view <engine>  添加对视图引擎(view) <engine> 的支持 (ejs|hbs|hjs|jade|pug|twig|vash) (默认是 jade 模板引擎)
    --no-view        创建不带视图引擎的项目
-c, --css <engine>   添加样式表引擎 <engine> 的支持 (less|stylus|compass|sass) (默认是普通的 css 文件)
    --git            添加 .gitignore
-f, --force          强制在非空目录下创建
-h, --help           输出使用方法

Created an Express application called myapp and used the ejs template engine

express --view=ejs myapp

Enter the app and install dependencies

cd myapp
npm install

On Windows, start the Express application with the following command:

set DEBUG=app:* & npm start

Under MacOS or Linux, use the following command to start the Express application:

DEBUG=app:* npm start

Use the express command to quickly create a project directory from

The name of the express project folder -e If you use the command line to enter the project directory, execute in sequence:

express app -e
cd app
cnpm install

At this time, you can also see the file structure under the app folder;

bin: 启动目录 里面包含了一个启动文件 www 默认监听端口是 3000 (直接node www执行即可)
node_modules:依赖的模块包
public:存放静态资源
routes:路由操作
views:存放ejs模板引擎
app.js:主文件
package.json:项目描述文件

The first Express app "Hello World"

Here, instead of using the scaffolding built by npm, we create a new app.js file directly in the main directory as we did at the beginning.

Enter in app.js

const express = require('express');     //引入express模块
var app= express();     //express()是express模块顶级函数

app.get('/',function(req,res){
    
          //访问根路径时输出hello world
    res.send(`<h1 style='color: blue'>hello world</h1>`);
});

app.listen(8080);       //设置访问端口号

After entering the project folder from the command line, type

npm run start/npm start

That is, the server has been turned on, and then you only need to run http://localhost:3000/ in the browser to access the data after the server gets the response

2. Introduction to template engine


Compared with the jade template engine, ejs has not made structural changes to the original HTML language, but has made some modifications in its interactive data, which is simpler and easier to use than jade. Therefore, its learning cost is very low. You can also refer to ejs official website: https://ejs.bootcss.com/
(1) Server dyeing, backend nested templates, backend rendering templates, SSR (backend assembles pages)

  • Do a good job of static pages and dynamic effects.
  • Provide the front-end code to the back-end, and the back-end needs to delete the static html and the fake data in it to dynamically generate the html content through the template

(2) Separation of front and rear ends, BSR (assembly page in the front end)

  • Do a good job of static pages and dynamic effects.
  • json simulation, ajax, dynamically create pages,
  • Real interface data, joint debugging before and after.
  • Provide the front end to the back end static resource folder

Server-side rendering can be seen in the source code, client-side rendering cannot be seen in the source code

3. Basic use of ejs


The following settings need to be made in the application to allow Express to render template files:
insert image description here

Here we use the following configuration file:

Basic ejs operations can be achieved in the following ways:
app.js file:

const express=require("express");
const ejs=require("ejs");
const fs=require("fs");

var app=express();

//引用ejs
app.set('views',"./views");  //设置视图的对应目录
app.set("view engine","ejs");       //设置默认的模板引擎

app.get("/",function(req,res){
    
    
    res.render("index",{
    
    title: "<h4>express</h4>"});
    //会去找views目录下的index.ejs文件
});

app.listen(8080);

ejs file:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title></title>
    </head>
    <body>
        <% for(var i=0;i<10;i++){ %>
            <%= i %>
        <% } %>
        <!-- 获取变量 -->
        <div class="datas">
            <p>获取变量:</p>
            <%- title %>
            <%= title %>
        </div>
    </body>
</html>

From this we can know:

<% xxx %>:里面写入的是js语法,
<%= xxx %>:里面是服务端发送给ejs模板转义后的变量,输出为原数据
<%- xxx %>:里面也是服务端发送给ejs模板后的变量,解析html
如果写html的注释,那样会在源码中显示,下面这种ejs注释不会在源码中显示
<%# 注释标签,不执行、不输出内容 %>

Similarly, the res.render() function also supports callbacks:

res.render('user', {
    
     name: 'Tobi' }, function(err, html) {
    
    
  console.log(html);
});

In this way we can see the content of html.

About res.redirect()

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

router.get('/', (req, res) => {
    
    
  res.render('login', {
    
    
    isShow: false,
    error: '',
  });
});

router.post('/', (req, res) => {
    
    
  if (req.body.username === 'ds' && req.body.password === '123') {
    
    
    console.log('登录成功');
    // res.send("成功")
    // 重定向到home
    res.redirect('/index');
  } else {
    
    
    console.log('登录失败');
    res.render('login', {
    
     error: '用户名密码不匹配', isShow: true });
  }
});

module.exports = router;

4. Various meanings of ejs tags


<% '脚本' 标签,用于流程控制,无输出。
<%_ 删除其前面的空格符
<%= 输出数据到模板(输出是转义 HTML 标签)
<%- 输出非转义的数据到模板
<%# 注释标签,不执行、不输出内容
<%% 输出字符串 '<%'
%> 一般结束标签
-%> 删除紧随其后的换行符
_%> 将结束标签后面的空格符删除
<% %>流程控制标签( 写的是if else,for)
<%= %>输出标签(原文输出HTML标签)
<%- %>输出标签(HTML会被浏览器解析)
<%# %>注释标签
<%- include(user/show',{user: user) %> 导入公共的模板内容

The above is the basic usage of ejs. In the future, the database operation will directly return the json data from the server to the template engine;

5. Import public template styles


header.ejs

<header>
  我是公共样式
  <div>
    <% if(isShowSchool) {
    
    %>
    <h1>校园招聘</h1>
    <% } %>
  </div>
</header>

index.ejs

<%- include("./header.ejs",{ isShowSchool:true }) %> index <%# 我的注释 %>

insert image description here

Guess you like

Origin blog.csdn.net/weixin_43094619/article/details/131921925