I am trying to dynamicly include one of my partials, using EJS. I render a template like so:
Router
router.get('/', noteController.getNotes, (req, res, next) => {
return res.render(template, {'page':'all'})
})
And am trying to include a partial in this template, based on the variable "page".
template.ejs
<% include %><%= page %><% .ejs %>
This however does not work. I have tried multiple methods, to no avail. Any help is much appreciated.
Simply:
<%- include(page) %>
or if it's in partials
folder:
<%- include('partials/'+page) %>
P.S. don't forget to declare view engine to be ejs
:
app.set('view engine', 'ejs');
From official source :
<%- Outputs the unescaped value into the template
You'll likely want to use the raw output tag (<%-) with your include to avoid double-escaping the HTML output.
for example using for Login page
app.get('/login', (req, res)=>{
res.render('layout', {page: 'login'})
})
here is simple 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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With