Search code examples
node.jsheaderejsfooterpartials

Why views is not identified when including it in an .ejs file?


This is my folder structure

Folder Structure

I have included my header.ejs and footer.ejs file like this:
<% include views/partials/header %> and <% include views/partials/footer %>

but its showing me the following error:
Error: Could not find the include file "views/partials/header"

but when I write

<% include partials/header %> and <% include partials/footer %>

Its finding the file and everything works fine.

Also: <% include /partials/header %> is not working

What is the issue here and why?

Kindly share any link/resource or any new concept regarding do this that needs to be understand :)


Solution

  • In your app.js you might have this

    app.set('views', path.join(__dirname, 'views'));
    app.set('view engine', 'ejs');
    

    So these lines set your view engine to ejs and also set your apps view folder to something like

    /Users/Usama/Projects/YelpCamp/views
    

    Now your app knows which is the views folder or from where to render views

    So in any for your views files, you can directly use

    <% include partials/header %> and <% include partials/footer %>

    no need for /views/partials/footer or if you add this Node.js looks for

    /Users/Usama/Projects/YelpCamp/views/views/partials/footer
    

    And this is why you get the error

    Error: Could not find the include file "views/partials/header"

    And in the second case <% include /partials/header %> because of / it looks inside the root folder.