Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EJS dynamic include

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.

like image 978
n0rd Avatar asked May 29 '17 22:05

n0rd


2 Answers

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.

like image 154
num8er Avatar answered Nov 07 '22 16:11

num8er


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>
like image 37
Văn Thảo Avatar answered Nov 07 '22 18:11

Văn Thảo