Pass variable to EJS include

Ruairi O'Brien picture Ruairi O'Brien · Jan 11, 2014 · Viewed 17.1k times · Source

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

Answer

Rick picture Rick · Oct 7, 2015

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'
    });
});