Reputation:
I've recently started developing in node.js, and so far I've got the basics down (routes, authentication, views, etc). I'm now wanting to organize my template a little better and so I'd like to find a way to load a partial based upon a parameter.
In my app, I've got this;
freeway.get('/login', function(req,res){
res.render('login');
});
What I'd like is to be able to pass in a parameter that points to a partial and have my view render it, something like this;
freeway.get('/login', function(req,res){
res.render('index', {reqpage: "login"});
});
My index view holds my main template which is primarily made up of hard-coded partials (though some have some display logic such as user-specific elements if a user is logged in). I'd like to expand this further and dynamically pass in a partial from my app to the index view, as opposed to having several essentially duplicate templates with only slightly varying contents.
I tried the following without success;
1) <%= reqpage %>
2) <% include reqpage %>
3) <% include <%= reqpage %> %>
In any case, they either cause the application to raise an error (implying the partial wasn't found) or render the path as a string. I even tried the following hoping it'd interpret it as code to render a partial, but alas no such luck;
res.render('index', {reqpage: "<% include login %>"});
Any ideas, or is Express + EJS simply not designed with this in mind?
Upvotes: 1
Views: 301
Reputation:
Thanks to the link provided by mscdex (https://github.com/visionmedia/ejs/issues/93), the solution is simple, though it does require you to directly edit the EJS lib files.
For the sake of others trying to find a solution, I'll paraphrase it here. This code is valid for version 1.0.0 of EJS.
1) In node_modules\ejs\ejs.js
at line 215, the following needs to be added;
if(options[name])
var path = resolveInclude(options[name], filename);
else
The line after the else would read var path = resolveInclude(name, filename);
2) In node_modules\ejs\lib\ejs.js
at line 163, the same code as above should be added.
3) Within your node.js application route, you then add a variable pointing to the partial you wish to render like so;
res.render('index', {reqpage: "login"});
4) Finally, within your index view (as per this example), you should add a standard include as such;
<% include reqpage %>
Consideration for expansion
include
to dynamic
to allow you to easily identify which partials are static within your view and which are passed in as variables.This change is as easy as changing it from 'include' to 'dynamic' within EJS lib. Due to the way EJS detects 'include', you can't use 'include_dyn' (or anything with 'include' in it) without refactoring the code.
Upvotes: 1