I have a global header used in a couple of places and I was trying to define its location in a variable that could be passed when rendering a template.
Something like:
var headerLocation = 'some/location/header.ejs'; res.render( viewDir + '/index', { header: headerLocation } );
And in a template file:
<% include header %>
header being the value passed in with the render.
It doesn't seem to be possible but maybe I missed something so thought I'd ask here.
EDIT:
This is mentioned in comments on answers below but to summarize, this is now available in version 2 of EJS.
See here: https://github.com/mde/ejs#includes And related discussion here: https://github.com/tj/ejs/issues/93
Now you can include them in your views. Use <% - include( 'RELATIVE/PATH/TO/FILE' ) %> to embed an EJS partial in another file. The hyphen <%- instead of just <% to tell EJS to render raw HTML. The path to the partial is relative to the current file.
Partials are basically just views that are designed to be used from within other views. They are particularly useful for reusing the same markup between different views, layouts, and even other partials. <%- partial('./partials/navbar.ejs') %>
EJS (Embedded JavaScript Templating) is one of the most popular template engines for JavaScript. As the name suggests, it lets us embed JavaScript code in a template language that is then used to generate HTML.
Here is some demo code that can accomplish dynamic includes.
View
<div flex class="main-container"> <%- include(page) %> </div>
Router
router.get('/', function (req, res, next) { res.render('pages/index', { page: 'home' }); });
This feature has been added: if it is not path (file not found), it is evaluated as variable name. https://github.com/visionmedia/ejs/pull/156
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With