我尝试像这样用 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"
...
文件夹结构如下:
你能告诉我为什么吗?我也试过这些案例,但没有希望:
<% 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")%>
但我当然不想使用它。
最佳答案
包含是相对于当前模板的。为了让引擎知道当前的模板路径,应该使用 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'); -%>
关于node.js - EJS - 包含返回找不到包含文件 "header.ejs",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50874226/