我的 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 模板。对于您的示例,它应该是:
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>
关于node.js - 如何将变量传递给 ejs.compile,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15201724/