EJS include file relative to project root

落爺英雄遲暮 提交于 2019-12-21 09:33:36

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/38487980/ejs-include-file-relative-to-project-root

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!