EJS在相对于设置视图路径的嵌套目录中包括部分内容 [英] EJS including partials in nested directories relative to set views path
问题描述
当前,我使用Express with EJS作为模板引擎.我的问题是,相对于嵌套视图中当前目录的路径,而不是相对于设置基本视图目录而言的路径,而无需借助黑客手段.
Currently I'm using Express with EJS as the templating engine. My issue is the path being relative to the current directory within nested views instead of the set base view directory without resorting to hacks.
我的views目录的结构如下
My views directory is structured as the following
+--/views
|
+--partials/
| |
| +--header.ejs
| +--footer.ejs
|
+--pages/
| |
| +--blog/
| | |
| | +--new.ejs
| | +--show.ejs
| |
| +--landing.ejs
| +--(More files)
|
+--index.html
我正在用express设置视图目录
I am setting a views directory in express
app.set('views',path.join(__ dirname,'views'));
在我使用的pages/landing.ejs中
In pages/landing.ejs I use
<%包括../partials/header%>
在更深层的嵌套视图中,例如pages/blog/new.ejs
In deeper nested views such as pages/blog/new.ejs
<%包括../../partials/header%>
并且有效,我的意图是使用基本路径是相对于两个文件中的set view目录的,如下所示:
and it works, my intention is to use with the base path is relative to the set view directory in both files as follows:
<%包括partials/header%>
EJS本身支持吗?
推荐答案
我找到了解决方案.我不知道如果您在在线站点上使用它会发生什么情况.
I find a solution. I don't know what happens if you use it on an online site!.
- 首先创建一个名为
app.locals.js
的文件,并在其中写入以下代码:
- First create a file named
app.locals.js
and write this code inside it:
module.exports = {
static: process.cwd() + "/static/",
views: process.cwd() + "/views/",
layouts: process.cwd() + "/views/layouts/",
pages: process.cwd() + "/views/pages/",
partials: process.cwd() + "/views/partials/",
components: process.cwd() + "/views/components/",
}
- 在
app.js
文件中:
const express = require("express");
const appLocals = require("./app.locals");
const app = express();
app.locals = appLocals;
- 使用方式如下:
<%- include(components + "post.ejs") %>
<%- include(partials + "header.ejs") %>
您无需在 .ejs
文件中导入任何内容.您可以直接访问 components
, partials
等.
You don't need to import anything in .ejs
files. You can directly access the components
, partials
and etc.
如果您了解更多信息,并且可以改进代码,请发表评论或其他内容.谢谢.
If you know more, if you can improve the code, please write a comment or something. Thanks.
这篇关于EJS在相对于设置视图路径的嵌套目录中包括部分内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!