ejs模板的三种用法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| const ejs = require('ejs'); const path = require('path');
const html = '<div><%= user.name %></div>' const options = {} const data = { user: { name: 'io' } }
const template = ejs.compile(html, options); const compiled = template(data) console.log(compiled);
const rendered = ejs.render(html, data, options); console.log(rendered);
const renderedfile = ejs.renderFile(path.resolve(__dirname, './index.html'), data, options); renderedfile.then(file => console.log(file))
|
ejs不同标签的含义
<% if(user){ %> <% } %> ‘脚本’标签,用于流程控制,无输出
<%_ %> 删除前面的空格
<%= user.name %> 输出数据到模板(转义字符, HTML标签)
<%- %> 输出非转义字符
<%# 这是注释%> 注释
%> 结束标签
<%% 输入字符串’<%’
-%> 删除紧随其后的换行符
<% _%> 将结束标签后的空格删除
包含
1 2
| <div>footer: user is <%= user.name %> </div>
|
1
| <%- include('./footer.html', {user}) %>
|
分隔符
1 2 3 4
| const options = { delimiter: '?' }
|
fileloader
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
|
ejs.fileLoader = function (filePath) { console.log('fileLoader', filePath); const content = '<div>footer: user is <?= user.name ?> </div>'+fs.readFileSync(filePath, 'utf8').toString(); return content; }
ejs.renderFile(path.resolve(__dirname, './index.html'), data, options, (err, file) => { console.log(file); });
|