EJS nightmare -- cannot include external view

Viewed 164

There never seems to be an easy way of including external files in EJS.

I have my project structured like this. So simple it hurts:

/lib/ejs-template.ejs

/views/home.ejs
/views/header.ejs

Inside home.ejs I must include header.ejs. I am mercifully following their documentation: https://ejs.co/#docs and include the file this way because "Includes are relative to the template with the include call",

<%- include("header") %>

Inside ejs-template.ejs I am compiling the template like this:

module.exports = (target, vars = {})=>{
    return Ejs.compile( Fs.readFileSync(`${__dirname}/../views/${target}.ejs`, {encoding: 'utf-8'}), {
        views: [ Path.resolve('../views') ],
    })(vars)
}

Yet I get this error!

Error: ejs:38
    36| <body>
    37|
 >> 38| <%- include("header") %>
    39|
    40| <main class="container">
    41|     <h4>Some stuff</h4>

Could not find the include file "header"
    at getIncludePath ([redacted]\server\node_modules\ejs\lib\ejs.js:183:13)
    at includeFile ([redacted]\server\node_modules\ejs\lib\ejs.js:309:19)
    at include ([redacted]\server\node_modules\ejs\lib\ejs.js:690:16)
    at eval (eval at compile ([redacted]\server\node_modules\ejs\lib\ejs.js:662:12), <anonymous>:12:17)
    at anonymous ([redacted]\server\node_modules\ejs\lib\ejs.js:692:17)
    at module.exports ([redacted]\server\util\ejs-template.js:13:7)
    at [redacted]\server\route\site.js:13:18
    at Layer.handle [as handle_request] ([redacted]\server\node_modules\express\lib\router\layer.js:95:5)
    at next ([redacted]\server\node_modules\express\lib\router\route.js:137:13)
    at module.exports ([redacted]\server\middleware\isLoggedIn.js:8:9) {
  path: ''
}

I have set the views path in the compiling options. I have tried with/without path. I've also tried with root set at the same exact views path.

What am I missing? The documentation is lax and offers no clues regarding this.

2 Answers

as I understood you are facing issue with include header portion in main view file. I used below code for same.

<body>
    <%- include("header"}) %>
    <h1><%= title %></h1>
    <p>Welcome to <%= title %></p>
    <button>Button</button>
</body>

above script is you home.ejs and you can create header.ejs. you can include like above

Related