How can I pass variable to ejs.compile

此生再无相见时 提交于 2019-12-04 11:13:06

问题


My bottom_index.ejs looks like that:

<div>The bottom section</div>

In my code I declare ejs:

ejs = require('ejs');

Then compile the function:

var botom_index_ejs =
ejs.compile(fs.readFileSync(__dirname + "/../views/bottom_index.ejs", 'utf8'));

and then call it to get rendered html:

botom_index_ejs()

It works fine!

Now I would like to change my template to:

<div><%= bottom_text %></div>

and be able to pass the parameter (bottom_text) to the bottom_index.ejs

How should I pass the parameters?

Thanks!


回答1:


Parameters are passed to EJS template as a JS plain object. For your example it sholud be:

botom_index_ejs({ bottom_text : 'The bottom section' });

Update:

test.js

var fs = require('fs');
var ejs = require('ejs');
var compiled = ejs.compile(fs.readFileSync(__dirname + '/test.ejs', 'utf8'));
var html = compiled({ title : 'EJS', text : 'Hello, World!' });
console.log(html);

test.ejs

<html>
    <head>
        <title><%= title %></title>
    </head>
    <body>
        <p><%= text %></p>
    </body>
</html>


来源:https://stackoverflow.com/questions/15201724/how-can-i-pass-variable-to-ejs-compile

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