I liked the concept of partials in Express; with 3 they are no more. Luckily someone added support for them in a separate module. I’m assuming the use of ejs as template engine (which is the one I always use).
Adding support is easy:
Add
“express-partials”:”*”
to your package.json or run;
npm install express-partials
To the definitions (in your app.js) add on top;
, partials = require(‘express-partials’)
Under your app=express() definition add;
app.use(partials());
Make sure to add it above the other app.use() commands; I didn’t check why yet, but adding it under others will not make partials function.
Now you are all set up to use partials!
Some simple cases:
res.render(‘index’); // renders index.ejs in <%- body %> variable of layout.ejs
res.render(‘index’, {layout:mobile}); // renders index.ejs in <%- body %> variable of mobile.ejs
res.render(‘index’); // where index contains <%- partial(‘user’, {somevar:’hello’}) %> renders user.ejs inside index.ejs which is rendered in the <%- body %> variable of layout.ejs
Be the first to leave a comment. Don’t be shy.