egg學習筆記(2)--靜態資源,模板(ejs),路由傳值
阿新 • • 發佈:2018-12-10
目錄結構
安裝ejs
cnpm install egg-view-ejs --save
ejs配置
//config/plugin.js
'use strict';
exports.ejs = {
enable: true,
package: 'egg-view-ejs',
};
//config/config.default
'use strict'; module.exports = appInfo => { const config = exports = {}; // use for cookie sign key, should change to your own and keep security config.keys = appInfo.name + '_1537172517005_2221'; // add your config here config.middleware = []; config.view = { mapping: { '.html': 'ejs', }, }; return config; };
controller
//constroller/news.js
'use strict'; const Controller = require('egg').Controller; class NewsController extends Controller { async index() { let name = this.ctx.query.name; let id = this.ctx.params.id; let list = [1,2,3]; await this.ctx.render('news',{ name, id, list }) } } module.exports = NewsController;
router
//router.js
router.get('/news', controller.news.index);
router.get('/news/:id', controller.news.index);
view
//news.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <link rel="stylesheet" href="/public/css/basic.css"> <title>Document</title> </head> <body> <p>query:<%= name %></p> <p>params<%= id %></p> <ul> <% for(var i=0;i<list.length;i++){ %> <li><%= list[i]%></li> <% } %> </ul> <img src="/public/images/1.jpg" alt=""> </body> </html>
get,query傳值
get,params傳值
靜態資源