如何将变量传递给ejs.compile

Ale*_*der 10 ejs node.js

我的bottom_index.ejs看起来像这样:

<div>The bottom section</div>
Run Code Online (Sandbox Code Playgroud)

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

ejs = require('ejs');
Run Code Online (Sandbox Code Playgroud)

然后编译函数:

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

然后调用它来渲染html:

botom_index_ejs()
Run Code Online (Sandbox Code Playgroud)

它工作正常!

现在我想将模板更改为:

<div><%= bottom_text %></div>
Run Code Online (Sandbox Code Playgroud)

并能够将参数(bottom_text)传递给bottom_index.ejs

我应该如何传递参数?

谢谢!

Vad*_*hev 21

参数作为JS普通对象传递给EJS模板.对于你的例子它sholud是:

botom_index_ejs({ bottom_text : 'The bottom section' });
Run Code Online (Sandbox Code Playgroud)

更新:

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);
Run Code Online (Sandbox Code Playgroud)

test.ejs

<html>
    <head>
        <title><%= title %></title>
    </head>
    <body>
        <p><%= text %></p>
    </body>
</html>
Run Code Online (Sandbox Code Playgroud)