2013-03-04 245 views
7

我bottom_index.ejs看起来像这样:如何传递变量ejs.compile

<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

我应该如何传递参数?

谢谢!

回答

18

参数作为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> 
+0

我想和我有bottom_text是没有定义的。你能给一个小小的工作Hello World示例吗?使用“编译”功能对我来说很重要,而不仅仅是任何工作解决方案。谢谢。 – Alexander 2013-03-04 15:21:35

+0

查看答案更新 – 2013-03-04 15:42:52