简体   繁体   中英

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 .

I contains code like this (very classical in such a case) in 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). 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:

<% 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:

"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

删除“ ..”和“ .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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM