最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - EJS dynamic include - Stack Overflow

programmeradmin1浏览0评论

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.

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.

Share Improve this question edited May 29, 2017 at 23:09 n0rd asked May 29, 2017 at 22:51 n0rdn0rd 1331 gold badge3 silver badges13 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 15

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>
发布评论

评论列表(0)

  1. 暂无评论