之前,我们test模块的控制器已经可以直接使用 $this.body='Hello World!';返回数据,本章讲解如何结合NODEJS常用模板引擎返回页面。
MKOA的模板功能居于koa-views实现,支持绝大部分nodejs模板引擎,具体:https://github.com/tj/consolidate.js#supported-template-engines
我们使用ejs作为模板引擎,首先安装功能依赖:
~~~
npm install koa-views --save
npm install ejs --save
~~~
修改config.js文件,开启视图功能。(更多配置项查看具体MKOA文档)
~~~
,view_open:true
,view_engine:'ejs'//视图解析
~~~
在test模块下创建views文件夹。再创建index文件夹,以及myaction.html文件,文件内容如下:
~~~
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<%= msg %>
</body>
</html>
~~~
修改test/controller/index.js
~~~
module.exports = function($this){
let action={};
action['myaction']=function (){
return $this.display({msg:'VIEWS'});
};
return action;
};
~~~
生成器和async函数写法
~~~
module.exports = function($this){
let action={};
action['myaction1']=function *(){
yield $this.display({msg:'VIEWS'});
};
action['myaction2']=async function (){
await $this.display({msg:'VIEWS'});
};
return action;
};
~~~
重启项目,访问http://localhost:3000/test/index/myaction ,成功使用模板渲染。
**其他说明**
> display函数,支持两个参数,第一个为指定模板(可省略),省略使用与控制器路径对应的模板进行渲染;
~~~
$this.display({});//使用对应路径的模板进行渲染
$this.display('point/index',{});//指定当前模块下 views/point/index.html模板进行渲染
$this.display('common:point/index',{});//指定common模块下 common/views/point/index.html模板进行渲染
~~~
> views文件夹文件,如果没有对应生成器。但路由匹配成功,则会自动渲染输出。
更多配置查看文档。