Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EJS include file relative to project root

I am using Express and EJS to build a site and I have a directory structure somthing like:

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

In both of the index.html files shown in my example, the <% include ... %> command would be different, even if referencing the same included file.

Also if I were to say include header.ejs and then header.ejs has an include for another partial, the whole system breaks down because they are all looking for files in different locations.

To make management easier, I'm trying to find a single string to be able to reference the same included files regardless of what sub-directory the files may be in.

Ideally something like <% include /partials/header.ejs %> would be perfect. But that doesn't work.

Does anyone have any tricks or advice that could give the desired result here?

like image 489
FatalKeystroke Avatar asked Jul 20 '16 18:07

FatalKeystroke


People also ask

How do I include an EJS file in another EJS file?

Use <% - include( 'RELATIVE/PATH/TO/FILE' ) %> to embed an EJS partial in another file. The hyphen <%- instead of just <% to tell EJS to render raw HTML. The path to the partial is relative to the current file.

How do you set partials in EJS?

Including a partial in EJS is quite straightforward. You use <%- include( PARTIAL_FILE ) %> where the partial file is relative to the template you use it in. Note: The <%- %> tags allow us to output the unescaped content onto the page (notice the -).


1 Answers

Looks like this is not supported by EJS however i found a workaround for this problem. In the above setup the pain point is for all partial files you need to mention the relative paths and if you refactor code that becomes more pain. So rather mentioning the relative path at every include i declare a variable rootPath once, and there i give the path to reach home. So that at every include i can simply mention the relative path just like path from root.

For example in guide/index.ejs i mention the following in top of the ejs file

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

and and code in ejs file looks like below

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

Your HTML code

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

So in case i refactor index.ejs to some other folder all i need to do is change the value of rootPath

like image 114
karthikdivi Avatar answered Oct 01 '22 06:10

karthikdivi