EJS - 包含返回无法找到包含文件" header.ejs"

时间:2018-06-15 11:00:08

标签: node.js express ejs

我尝试用这样的ejs渲染html

const ejs = require('ejs'),
      fs = require('fs'),
      str = fs.readFileSync(`${__dirname}/../mail_templates/test.ejs`, 'utf8');

console.log(ejs.render(str, {name: 'abc'});

test.ejs

<%- include(`header.ejs`)%>
...

但得到了这个错误:

Error: ejs:1
>> 1| <%- include(`header.ejs`)%>

Could not find the include file "header.ejs"
...

以下是文件夹结构的外观:

enter image description here

你能告诉我为什么吗?我也试过这些案子,但没有希望:

<% include header.ejs %>
<% include header %>
<%- include('header.ejs'); -%>
<%- include('../mail_templates/header.ejs'); -%>
<%- include('mail_templates/header.ejs'); -%>
<%- include('./mail_templates/header.ejs'); -%>

唯一可行的方法是使用绝对路径:

<%- include("/Users/admin/Work/engine/mail_templates/header.ejs")%>

但我当然不想使用它。

1 个答案:

答案 0 :(得分:5)

包含与当前模板相关。为了让引擎知道当前的模板路径,应该使用filename选项指定它,例如:

const templatePath = `${__dirname}/../mail_templates/test.ejs`;
str = fs.readFileSync(templatePath, 'utf8');

ejs.render(str, {filename: templatePath, name: 'abc'});

然后它预计这些包含中的任何一个都会起作用:

<% include header.ejs %>
<% include header %>
<%- include('header.ejs'); -%>
<%- include('./header.ejs'); -%>