EJS – Include return Could not find the include file "header.ejs"


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


<%- 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:

enter image description here

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.


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

Answered By – Estus Flask

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published