Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass variable to EJS include

Tags:

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

like image 824
Ruairi O'Brien Avatar asked Jan 10 '14 23:01

Ruairi O'Brien


People also ask

How do I include in EJS?

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.

What is partials in node JS?

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') %>

What is .EJS file?

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.


2 Answers

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'     }); }); 
like image 98
Rick Avatar answered Oct 23 '22 09:10

Rick


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

like image 30
pr.nizar Avatar answered Oct 23 '22 10:10

pr.nizar