EJS dynamic include

Viewed 11110

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.

2 Answers

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>
Related