[英]How to include contents in EJS?
I am having some trouble with something that (I think) ought to be simple. 我在某些本来应该很简单的事情上遇到了麻烦。 My web app is a
Node.js
one with express
and ejs
. 我的web应用程序是一个
Node.js
一个有express
和ejs
。
I contains code like this (very classical in such a case) in index.js: 我在index.js中包含了这样的代码(在这种情况下非常经典):
var app = express();
app.use('/public', express.static(path.join(__dirname, '/public')));
app.set('port', (process.env.PORT || 5000));
app.use(express.static(__dirname + '/public'));
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
Now here is the issue I have. 现在这是我遇到的问题。
Among all my .ejs files, some happen to need the same code (written by me). 在我所有的.ejs文件中,有些恰好需要相同的代码(由我编写)。 In order to avoid repetition I want to have this code in a separate file and then include it when necessary, but I can't find the proper way to do it.
为了避免重复,我想将此代码存储在一个单独的文件中,然后在必要时将其包括在内,但是我找不到正确的方法。 I put the code in a file called Utils.ejs (in the partials folder) then used this:
我将代码放在一个名为Utils.ejs的文件中(位于partials文件夹中),然后使用了它:
<% include ../partials/Utils.ejs %>
but it does not work. 但它不起作用。 I then searched the net and tried a few variations, but found nothing working.
然后,我在网上搜索并尝试了几种变体,但没有任何效果。
Does any one know how I can do that? 有人知道我该怎么做吗?
For information about versions, here is what I have in my package.json file: 有关版本的信息,这是我的package.json文件中的内容:
"ejs": "^2.5.7",
"express": "~4.11.x",
"node": ">=4.3"
Do Not include the file extension while u import the partials 导入局部文件时不包括文件扩展名
Remove the .ejs
from the <% include ../partials/Utils.ejs %>
and try 从
<% include ../partials/Utils.ejs %>
删除.ejs
并尝试
删除“ ..”和“ .ejs”,并确保“ / partials / Utils /”位于公用文件夹中
<% include /partials/Utils %>
here in this line 在这行
app.set('views', __dirname + '/views');
make it 做了
app.set('views', __dirname + '/views/pages/');
this way it will work fine, you can access all view pages ( views/pages/
) directly, and your partial views ( views/partials/
) are also accessible from the pages folder. 这样就可以正常工作,您可以直接访问所有视图页面(
views/pages/
),也可以从pages文件夹访问您的部分视图( views/partials/
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.