express的模板引擎------ejs

express的模板引擎------ejs

ejs 模板引擎。
  1. 下载安装:
    cnpm i ejs -S

  2. 添加设置

app.set("view engine","ejs")

 
  1. 新建文件夹
    在app.js同级目录下新建一个views文件夹(名字不可以改,要修改的话需要再添加一条设置。)
    在view文件夹下新建一个ejs后缀的文件,在里面可以书写HTML内容。

  2. 响应ejs模板内容

 res.render("views里的文件名(不加路径和后缀)",{渲染的变量})
  1. 不是使用send方法,而是要用render方法,
    render方法有两个参数:
    第一个参数:ejs模板的路径,相对于views。
    第二个参数:需要往ejs模板中添加的数据

ejs的基础语法:

  1. ejs支持简单的js语法:if判断,循环语句
  2. 插值语句:
 <%= 变量名 %>
 if else 语句
  <% if(条件){ %>
      html代码
   <% } %>
 循环语句:
  <% arr.foreach((item,index)=>{ %>
       html代码
     <% }) %>

html

<!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>
    <form action="http://localhost:3000/index" method="POST">
        <p><input type="text" name="username"></p>
        <p><button type="submit">提交</button></p>
    </form>
</body>
</html>

ejs

<!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>
    <style>
        h1{
            color: cornflowerblue;
        }
    </style>
</head>
<body>
    <h1>欢迎 <span
     <% if(name=="zhangsan"){%>
        style = "color:crimson"
      <% } %> ><%=name %> </span>来到首页</h1>
</body>
</html>

js

const express = require("express");
const path = require("path");
let app = express();
// 请求post参数
app.use(express.urlencoded({ extended: false }));
// 使用静态访问,获取pubic
app.use(express.static(path.join(__dirname, "public")));
// 定义ejs模块
app.set("view engine","ejs")
app.post("/index", (req, res) => {
    res.render("local", { name:req.body.username });
})
app.listen(3000, () => {
    console.log("创建成功!");
})

在这里插入图片描述

在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值