如何将变量传递给ejs.compile函数

11
我的bottom_index.ejs看起来像这样:
<div>The bottom section</div>

在我的代码中,我声明了ejs:

ejs = require('ejs');

然后编译该函数:
var botom_index_ejs =
ejs.compile(fs.readFileSync(__dirname + "/../views/bottom_index.ejs", 'utf8'));

然后调用它以获取渲染的 HTML:
botom_index_ejs()

它很好用!

现在我想将我的模板更改为:

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

我希望你能够传递参数(bottom_text)到 bottom_index.ejs 文件中。请问该如何传递参数?谢谢!

1个回答

24
参数以JS纯对象的形式传递给EJS模板。对于您的示例,应该是这样的:
botom_index_ejs({ bottom_text : 'The bottom section' });

更新:

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>

我尝试过了,但遇到 bottom_text 未定义的错误。请问你能给个简单可用的 Hello World 示例吗?对我来说使用“compile”函数非常重要,而不仅仅是任何可行的解决方案。谢谢。 - Alexander

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接