koa页面渲染
上一节我们通过koa的路由中间件,在上下文的body属性中渲染页面内容,但那只是基本的一些字符串内容,而我们前端所用的页面,或者浏览器所渲染的,基本都是html标签的页面文件,如果想在koa路由中渲染标签内容,又如何做呢,接下来看代码
1、渲染html内容
就是在body中渲染标签文本,用es6的模版语法把html文本包起来就可以了。
const Koa = require('koa');
const Router = require('koa-router');
const app = new Koa();
const router = new Router();
app.use(async (ctx, next) => {
await next();
});
router.get('/', async ctx => {
ctx.type = `text/html;charset=utf-8`;
ctx.body = `
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title></title>
</head>
<body>
<h2>test</h2>
</body>
</html>
`;
});
//启动路由
app.use(router.routes());
app.use(router.allowedMethods());
app.listen(3000);
重启服务,刷新浏览器,就会看到浏览器显示加粗的test
字样。
众所周知,日常开发中,页面需要展示的标签内容有时候是很庞大的,而这时候body又不可能去填写那么多的内容,这时候就得益于编程中的模块化思想了:就是把想要的内容当成一个模块引入。
2、渲染js标签文件
接下来新建一个html.js
文件,把上面要展示的html内容复制过去
module.exports = `
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title></title>
</head>
<body>
<h2>test</h2>
</body>
</html>
`;
然后在app.js
中引入
const Koa = require('koa');
const Router = require('koa-router');
const testTpl = require('./html.js');
console.log(testTpl);
const app = new Koa();
const router = new Router();
app.use(async (ctx, next) => {
await next();
});
router.get('/', async ctx => {
ctx.type = `text/html;charset=utf-8`;
ctx.body = testTpl;
});
//启动路由
app.use(router.routes());
app.use(router.allowedMethods());
app.listen(3000);
重启服务器,刷新浏览器,这样页面就能展示同样的内容。
3、模版渲染
虽然当作模块引入也能达到我们想要的效果,但html.js
毕竟只是一个js文件,跟我们正常使用的html文件还是不一样,如果想要使用html文件,就要使用本节需要用到的koa-views
中间件了。
- 首先下载
yarn add koa-views ejs
,其中ejs
是模版库,用来渲染模版文件的,具体用法参考官网。 - 然后在项目根目录新建
views
文件夹,并在该目录下新建index.ejs
和news.ejs
、blocks/header.ejs
文件,文件内的内容如下
<!DOCTYPE html>
<html lang="en">
<!-- index.ejs -->
<head>
<meta charset="UTF-8" />
<title>首页</title>
</head>
<body>
<!-- 模版语法,include包含的路径是以views配置的文件夹为准的 -->
<%- include('blocks/header.ejs') %>
<p><%= commonData %></p>
<p><%= title %></p>
<ul>
<% for(var i = 0;i < list.length;i++){ %>
<li><%= list[i] %></li>
<% } %>
</ul>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<!-- news.ejs -->
<head>
<meta charset="UTF-8" />
<title>首页</title>
</head>
<body>
<!-- 模版语法,include包含的路径是以views配置的文件夹为准的 -->
<%- include('blocks/header.ejs') %>
<p><%= commonData %></p>
<p><%= title %></p>
<ul>
<% for(var i = 0;i < list.length;i++){ %>
<li><%= list[i] %></li>
<% } %>
</ul>
</body>
</html>
<!-- header.ejs -->
<h1>这是一个头部模块</h1>
- 最后配置
app.js
文件,使用模版文件
const Koa = require('koa');
const Router = require('koa-router');
const Views = require('koa-views');
const testTpl = require('./html.js');
const app = new Koa();
const router = new Router();
// 配置模版引擎中间件,.html和.ejs配置取其一
// 匹配.html后缀模版文件
// app.use(
// Views('views', {
// map: { html: 'ejs' }
// })
// );
// 匹配.ejs后缀模版文件
app.use(
Views('views', {
extension: 'ejs'
})
);
app.use(async (ctx, next) => {
await next();
});
// 配置公共信息的中间件
app.use(async (ctx, next) => {
ctx.state.commonData = '中间件:公共信息配置,其中commonData是随意起的名字';
ctx.state.commonData2 =
'中间件2:公共信息配置,其中commonData2是随意起的名字';
// 要显式向下继续执行
await next();
});
// 配置首页模版信息
router.get('/', async ctx => {
const title = 'Hello world !';
const list = ['Charles', 'Jack', 'Black', 'Lusy'];
/**
* 利用上下文的render函数渲染匹配到的文件
* index:匹配的中间件views文件夹下的文件名,后缀是.html或.ejs
* {title,list}:匹配的文件中使用的变量
*/
await ctx.render('index', { title, list });
});
router.get('/news', async ctx => {
await ctx.render('news', {});
});
router.get('/html', async ctx => {
ctx.type = `text/html;charset=utf-8`;
ctx.body = testTpl;
});
//启动路由
app.use(router.routes());
app.use(router.allowedMethods());
app.listen(3000);
重启node,刷新浏览器
![](https://img.haomeiwen.com/i5644085/6214e3746b76e574.png)
输入对应的
/news
和/html
也能看到对应的内容,完美!。到这里,koa模版渲染中间件的基本使用就完成了。
Ps
模版文件报错,要注意模版文件中路径的引入
/*
出现类似这个错误:
SyntaxError: Unexpected token . in /PATH/index.ejs while compiling ejs
If the above error is not helpful, you may want to try EJS-Lint:
https://github.com/RyanZim/EJS-Lint
Or, if you meant to create an async function, pass `async: true` as an option.
是写法 <% include ../PATH/files.ejs %> 导致
要改成 <%- include('../PATH/files.ejs') %>
而且模版文件不能写注释: <!-- 注释内容 -->
*/
网友评论