ejs模块的使用

概念
是服务器渲染的一种方式
基本使用
  1. 初始化文件夹,并生成package.json配置文件
    npm init -y
Wrote to D:\four\Class\Class0912\codetest0921\2code\package.json:

{
  "name": "2code",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}

2.下载需要的模块
cnpm i express ejs consolidate --save-dev

$ cnpm i express ejs consolidate --save-dev
√ Installed 3 packages
√ Linked 63 latest versions
√ Run 0 scripts
√ All packages installed (69 packages installed from npm registry, used 2s(network 2s), speed 102.85kB/s, json 66(182.66kB), tarball 0B)

3.创建app.js

//1 引入模块
const express=require("express");
const ejs=require("ejs");
const consolidate=require("consolidate");
//2 创建
const app=express();
//3 配置
app.set("view engine","html");
app.set("views",'./views');
app.engine("html",consolidate.ejs);

app.get("/index",(req,rep,next)=>{
    rep.render("index1",{title:"我是张艺兴"});
})
app.listen(8080,()=>{
    console.log("服务已经启动")
})

4.index1调用

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <%=title%>
</body>
</html>
  1. 启动服务
$ nodemon app.js
[nodemon] 2.0.4
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,json
[nodemon] starting `node app.js`

6.访问
127.0.0.1:8080/index在这里插入图片描述

拓展
1 循环取数据
数据
 let data=[
    {
        url:"www.baidu.com",
        text:"百度"
    },
    {
        url:"www.sina.com",
        text: "新浪"
    },
    {
        url:"www.tencent.com",
        text:"腾讯"
    }
]
页面取值:
<% list.forEach((el)=>{ %>
<li>
    <a href="<%=el.url%>"><%=el.text%></a>
</li>
<% }) %>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值