2013-03-04 270 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