Pass variable to EJS include

北城以北 提交于 2019-12-03 09:40:47

This feature has been added: if it is not path (file not found), it is evaluated as variable name. https://github.com/visionmedia/ejs/pull/156

Here is some demo code that can accomplish dynamic includes.

View

<div flex class="main-container">
    <%- include(page) %>
</div>

Router

router.get('/', function (req, res, next) {
    res.render('pages/index', {
        page: 'home'
    });
});

Even though its an old question, answering it for others sake.

As per the github documentation, it seems EJS has no notion of blocks, only compile-time include. Since its compile time include, you need to hardcode the location.

So you are left with passing some flags and doing if checks in the header or parse the header as html and pass it to all the templates...

Old subject, but it may help someone.

The great thing about EJS is that it is just Javascript. So something like the following should work:

<%
const fs = require('fs');
const content = fs.readFileSync(partial);
%>
<%- content %>

Hope it helps.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!