EJS include file relative to project root

后端 未结 2 414
北海茫月
北海茫月 2021-01-02 03:43

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

+--www/
  |
  +--partials/
  | |
  | +--header.ejs
  | +--(a bun         


        
2条回答
  •  情书的邮戳
    2021-01-02 04:24

    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

提交回复
热议问题