EJS包含文件相对于项目根目录 [英] EJS include file relative to project root

查看:185
本文介绍了EJS包含文件相对于项目根目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Express和EJS构建网站,
我的目录结构如下:

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

在两个索引中在我的示例中显示的.html 文件中,即使引用了包含的相同内容,<%include ...%> 命令也会有所不同文件。

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

另外,如果我要说的话,先包含 header.ejs 然后是 header。 ejs 包含另一个部分的包含,整个系统崩溃,因为它们都在寻找不同位置的文件。

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.

理想情况是类似<%include /partials/header.ejs%> 是完美的。但这不起作用。

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?

推荐答案

EJS似乎不支持这种方法,但是我找到了解决此问题的方法。
在上面的设置中,问题的关键是所有部分文件都需要提及相对路径,并且如果重构代码会更麻烦。因此,宁愿在每个include都提及相对路径,我一次声明一个变量 rootPath ,然后在此给出到达首页的路径。这样,在每个收录中,我都可以简单地提及相对路径,就像从根开始的路径一样。

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.

例如,在 guide / index.ejs 我在ejs文件顶部提到了以下内容

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

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

,并且ejs文件中的代码如下所示:

and and code in ejs file looks like below

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

您的HTML代码

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

因此,如果我将index.ejs重构到其他文件夹,我要做的就是更改<$ c的值$ c> rootPath

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

这篇关于EJS包含文件相对于项目根目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆