EJS是一个简单高效的模板语言,通过数据和模板,可以生成HTML标记文本。可以说EJS是一个JavaScript库,EJS可以同时运行在客户端和服务器端,客户端安装直接引入文件即可,服务器端用npm包安装
ejs的安装
1.直接在项目中安装
cnpm install ejs
2.在用express创建项目时安装
express -e (项目名称)
ejs使用
1. JS 调用
ejs引用:
app.set(“view engine”,”ejs”);
JS 调用的方法主要有两个:
1.var template= ejs.compile(str, options);
[// => Function][6]
template(data); [//=> html][6]
- ejs.render(str,data, options);
[// => str ][6]
//or 把str data options都放在一个object中传入
ejs.render(allOptions);
2. ejs常用的一些语法
- 用<%…%>包含js代码
- 用<%=…%>输出变量 变量若包含 ‘<’ ‘>’ ‘&’等字符 会被转义
- 用<%-…%>输出变量 不转义
- 用<%- include(‘user/show’) %>引入其他模板 包含 ./user/show.ejs
- 用<%# some comments %>来注释,不执行不输出
- <%% 转义为 ‘<%’
- <% … -%> 删除新的空白行模式?
- <%_ … _%> 删除空白符模式
3.基本用法
//template.ejs:
<% if(comic) { %>
<h2><%=comic.name%></h2>
<% } %>
//test.js:
var comic = {name: 'one piece'};
// 渲染文件模板,
// comic.ejs 包含 header.ejs footer.ejs,
// 若include了文件 必须指定 filename参数 , 参数为文件路径,
// 文件所在目录为查找include资源的 path.diranme(specialFilepath)
var html = ejs.render( fs.readFileSync('comic.ejs', 'utf8'), {'comic': comic}, {filename: __dirname+'\\abc.js'});
console.log(html);
options参数
- cache 缓存编译后的函数(ejs.compile(..) ,需要 filename参数作为缓存的key
- filename 用于缓存的key,和include
- context 函数的执行上下文
- compileDebug 输出compile的信息来跟踪调试
- client 返回编译后的函数
- delimiter <% .. %> 指这里的%
- debug 输出ejs.compile()得到函数的函数体
- strict ejs.compile()返回的函数是否执行在严格模式
- with 是否使用 with(){..} 来访问本地变量
- localsName 保存本地变量的对象名,默认为locals
- rmWhitespace 移除多余空格
页面布局
ejs没有显式的支持布局功能,但是可以通过 include 页头页脚的方式,实现基本的布局。
//index.ejs:
<%- include('header'); %>
<h1>show content </h1>
<% if(testoption) { %>
<h2><%= testoption.name %></h2>
<% } %>
<%- include('footer') %>
//test.js:
var testoption = {name: 'one piece'};
var html = ejs.render( fs.readFileSync('index.ejs', 'utf8'), {'testoption': testoption}, {filename: __dirname+'\\abc.js'});