koa2模版初识——ejs
在koa2中是用ejs模版需要依赖中间件,koa-views。
npm install --save koa-views
安装模版引擎:
npm install --save ejs
编写ejs模版文件:<%= %> =:的意思是对中间的代码转义 ,还有一种是<%- %>:-号,是不转义。推荐使用<%= %>。更多关于ejs的使用,请参考ejs官方文档。
#view/index.ejs
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title><%= title%>title>
head>
<body>
<h1><%= title%>h1>
<div>
ejs welcome to <%= title%>
div>
body>
html>
编写koa文件,渲染ejs模版文件:
#ejs.js
const Koa=require('koa'); const views = require('koa-views') const path = require('path') const Router = require('koa-router') const app = new Koa(); const router = new Router(); app.use(views(path.join(__dirname,'./view'),{ extension:'ejs' })); router.get('/index', async ctx=>{ let title='hello koa2'; await ctx.render('index',{title}) }); app.use(router.routes(), router.allowedMethods()) app.listen(3333,()=>{ console.log('[demo] server is starting at port 3333') })
运行该文件:
node ejs.js
在浏览器中查看效果:
http://localhost:3333/index
OK,一个简单ejs模版使用完成。