前言
Express Generator生成的项目默认采用jade模板引擎,对于习惯html或者freemarker的小伙伴来说需要重新学习其语法,在本人的小项目 node-sorry选择是ejs(ps:演示地址)。
Element UI 是一套采用 Vue 2.0 作为基础框架实现的组件库,它面向企业级的后台应用,能够帮助你快速地搭建网站,极大地减少研发的人力与时间成本,具体用法请参考Element UI
安装
yarn add ejs// 或 cnpm install -save ejs
yarn安装方式
npm install -g yarn
cnpm安装方式
npm install -g cnpm --registry=https://registry.npm.taobao.org
修改app.js
...
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
...
路由route.js
...
router.get('/hello', function (req, res, next) {
res.render('./index', {title: 'express'});
});
...
页面index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>hello</title>
<meta name="description" content="">
<meta name="author" content="">
<!-- HTML5 shim, for IE6-8 support of HTML elements -->
<!--[if lt IE 9]>
<script src="http://apps.bdimg.com/libs/html5shiv/r29/html5.min.js"></script>
<![endif]-->
<!-- styles -->
<link href="css/style.css" rel="stylesheet">
</head>
<body>
hello world,<%= title %>
</body>
</html>
高级用法:利用模板生成文件
const fs = require('fs')
const path = require('path')
const rootPath = path.resolve(__dirname + "/..")
...
outputFilePath = "/public/cache/output.ass"
templatePath = rootPath + "/public/templates/test/template.ejs"
template = fs.readFileSync(templatePath, "utf8") //先读文件
renderedAssText = require('ejs').render(template, {
'sentences': sentences
})
fs.writeFileSync(rootPath + outputFilePath, renderedAssText)
...
ejs不局限于生成html,其他格式文件也可。在这里特别注意fs的路径,用绝对路径省事。。。