EJS includes file relative to project root

I use Express and EJS to create a site and I have a somthing like directory structure:

+--www/ | +--partials/ | | | +--header.ejs | +--(a bunch of ejs files) | +--guide | | | +--index.html | +--(other files) | +--index.html 

In both index.html files specified in my example, the <% include ... %> command will be different even if it refers to the same included file.

Also, if I said include header.ejs and then header.ejs has an include for another partial, the whole system breaks up because they all look for files in different places.

To simplify the management, I try to find one line in order to be able to refer to the same files, regardless of which subdirectory the files are in.

Ideally, something like <% include /partials/header.ejs %> would be ideal. But that does not work.

Does anyone have any tricks or tips that can give the desired result here?

+5
source share
1 answer

It seems that this is not supported by EJS, however I have found a workaround for this problem. In the above setup, the pain point is for all partial files that you need to mention relative paths, and if you use refactoring code that gets painful. Thus, instead of mentioning the relative path in each of them, I declare the rootPath variable once, and there I give the path to get to the house. So in each inclusion, I can simply specify the relative path as the path from root.

For example, in guide/index.ejs I mention the following at the top of the ejs file

<% var rootPath = '../'; %>

and the code in the ejs file looks below

<%- include(rootPath + 'partials/header'); %>

Your html code

<%- include(rootPath + 'partials/footer'); %>

So, in case I refactor index.ejs to some other folder I need to do is change the rootPath value

0
source

All Articles