如何将变量传递给ejs.compile [英] How can I pass variable to ejs.compile
本文介绍了如何将变量传递给ejs.compile的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的bottom_index.ejs看起来像这样:
My bottom_index.ejs looks like that:
<div>The bottom section</div>
在我的代码中,我声明ejs:
In my code I declare ejs:
ejs = require('ejs');
然后编译该函数:
var botom_index_ejs =
ejs.compile(fs.readFileSync(__dirname + "/../views/bottom_index.ejs", 'utf8'));
然后调用它以呈现html:
and then call it to get rendered html:
botom_index_ejs()
效果很好!
现在我想将模板更改为:
Now I would like to change my template to:
<div><%= bottom_text %></div>
并能够将参数(bottom_text)传递给bottom_index.ejs
and be able to pass the parameter (bottom_text) to the bottom_index.ejs
我应该如何传递参数?
谢谢!
推荐答案
参数作为JS普通对象传递到EJS模板。对于您的示例,它应该是:
Parameters are passed to EJS template as a JS plain object. For your example it sholud be:
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>
这篇关于如何将变量传递给ejs.compile的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文