Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using interpolation within Node.js EJS includes

My Express app is using EJS, and my views directory looks like this:

./views
  ./contents
    home.ejs
  ./includes
    header.ejs
    footer.ejs
  layout.ejs

I'm trying to load home.ejs in my layout.ejs view conditionally based on a local variable named contents in my routes/index.js. That file looks like this:

/*
 * GET home page.
 */

exports.index = function(req, res){
  res.render('index', { title: 'Home', contents: 'home.ejs' });
};

Ideally I could simply write (in layout.ejs):

<% include '/contents' + contents %>

where the trailing "contents" is the local variable which contains the relative path to the body text to load.

But alas, it appears EJS always interprets the text following an include directive literally, and there is no chance for any interpolation magic to happen.

I've also tried to no avail:

<% function yieldContent(contents){ %>
  <% var contentPath = 'contents/' + contents; %>
  <% include contentPath %>
<% }; %>
<% loadContent(); %>

Does anyone have a creative solution for conditionally including a view based on a variable passed in routes?

like image 580
bottles Avatar asked Aug 03 '12 23:08

bottles


People also ask

What is the use of EJS in node JS?

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.

What are partials in EJS?

When using the default view engine ( ejs ), Sails supports the use of partials (i.e. "view partials"). 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.


1 Answers

I think there is no way to do this kind of dynamic includes in EJS. It might break the separation of business logic and view. The solution can be to rendering the subtemplate in the controller, and passing its content to the layout.

For rendering subtemplate in the controller use something like this:

var ejs = require('ejs'),
, fs = require('fs')
, home = ejs.render(fs.readFileSync("contents/home.ejs", "utf-8"))
like image 193
levram Avatar answered Sep 19 '22 11:09

levram