EJS-包含返回找不到包含文件"header.ejs". [英] EJS - Include return Could not find the include file "header.ejs"

查看:73
本文介绍了EJS-包含返回找不到包含文件"header.ejs".的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试用这样的ejs渲染html

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

但是出现了这个错误:

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.

推荐答案

包含的内容是相对于当前模板的.为了使引擎知道当前的模板路径,应使用 filename 选项指定它,例如:

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'); -%>

这篇关于EJS-包含返回找不到包含文件"header.ejs".的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆