EJS - Include return Could not find the include file “header.ejs”

柔情痞子 提交于 2020-12-31 06:01:50

问题


I try to render html with ejs like this

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`)%>
...

But got this error:

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

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

Here is how the folder structure look like:

Can you tell me why? I also tried these cases but no hope:

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

The only case that work is to use the absolute path:

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

But of course I don't want to use this.


回答1:


Includes are relative to current template. In order for the engine to be aware of current template path, it should be specified with filename option, something like:

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

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

Then it's expected that any of these includes will work:

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


来源:https://stackoverflow.com/questions/50874226/ejs-include-return-could-not-find-the-include-file-header-ejs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!