我如何将variables传递给ejs.compile

我的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

我应该如何传递参数?

谢谢!

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

 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>