EJS dynamics include
I am trying to dynamically include one of my parts using EJS. I am creating a template like this:
router
router.get('/', noteController.getNotes, (req, res, next) => {
return res.render(template, {'page':'all'})
})
And I'm trying to include a partial in this template based on the "page" variable.
template.ejs
<% include %><%= page %><% .ejs %>
This does not work, however. I have tried several methods but to no avail. Any help is greatly appreciated.
+3
n0rd
source
to share
2 answers
Just:
<%- include(page) %>
or if it's in a folder partials
:
<%- include('partials/'+page) %>
Postscript don't forget to declare the view engine ejs
:
app.set('view engine', 'ejs');
+4
num8er
source
to share
eg for login page
app.get('/login', (req, res)=>{
res.render('layout', {page: 'login'})
})
here is just layout.ejs
<body>
<% include ./templates/nav %>
<div class="row">
<div class="col-md-2">
<% include ./templates/leftbar %>
</div>
<div class="col-md-8">
<%- include(page) %>
</div>
<div class="col-md-2">
<% include ./templates/rightbar %>
</div>
</div>
<% include ./templates/footer %>
</body>
login.ejs
<h1>Login</h1>
<form method="POST" action="/login">
<div class="form-group">
<label class="control-label">Username: </label>
<input class="form-control" type="text" name="username" placeholder="username">
</div>
<div class="form-group">
<label class="control-label">Password:</label>
<input class="form-control" type="text" name="password" placeholder="password" />
</div>
<input class="btn btn-info" type="submit" value="Login">
</form>
0
VΔn ThαΊ£o
source
to share