问题
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
回答1:
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
回答2:
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'
});
});
回答3:
Even though its an old question, answering it for others sake.
As per the github documentation, it seems EJS has no notion of blocks, only compile-time include. Since its compile time include, you need to hardcode the location.
So you are left with passing some flags and doing if checks in the header or parse the header as html and pass it to all the templates...
回答4:
Old subject, but it may help someone.
The great thing about EJS is that it is just Javascript. So something like the following should work:
<%
const fs = require('fs');
const content = fs.readFileSync(partial);
%>
<%- content %>
Hope it helps.
来源:https://stackoverflow.com/questions/21056275/pass-variable-to-ejs-include