如何在 Node.js 中呈现 EJS 模板文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8660659/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I render an EJS template file in Node.js?
提问by Headshota
I'm using Node.js and trying to render an EJS template file. I figured out how to render strings:
我正在使用 Node.js 并尝试呈现 EJS 模板文件。我想出了如何呈现字符串:
var http = require('http');
var ejs = require('ejs');
var server = http.createServer(function(req, res){
res.end(ejs.render('Hello World'));
});
server.listen(3000);
How can I render an EJS template file?
如何呈现 EJS 模板文件?
回答by ksloan
There is a function in EJS to render files, you can just do:
EJS 中有一个函数来渲染文件,你可以这样做:
ejs.renderFile(__dirname + '/template.ejs', function(err, data) {
console.log(err || data);
});
Source: Official EJS documentation
来源:官方 EJS 文档
回答by Amadan
var templateString = null;
var fs = require('fs');
var templateString = fs.readFileSync('template.ejs', 'utf-8');
and then you do your thing:
然后你做你的事情:
var server = http.createServer(function(req, res){
res.end(ejs.render(templateString));
});
回答by alessioalex
All you have to do is compile the file as a string (with optional local variables), like so:
您所要做的就是将文件编译为字符串(带有可选的局部变量),如下所示:
var fs = require('fs'), ejs = require('ejs'), http = require('http'),
server, filePath;
filePath = __dirname + '/sample.html'; // this is from your current directory
fs.readFile(filePath, 'utf-8', function(error, content) {
if (error) { throw error); }
// start the server once you have the content of the file
http.createServer(function(req, res) {
// render the file using some local params
res.end(ejs.render(content, {
users: [
{ name: 'tj' },
{ name: 'mape' },
{ name: 'guillermo' }
]
});
});
});
回答by Greg
There's a synchronous version of this pattern that tightens it up a little more.
这种模式有一个同步版本,可以稍微收紧一点。
var server = http.createServer(function(req, res) {
var filePath = __dirname + '/sample.html';
var template = fs.readFileSync(filePath, 'utf8');
res.end(ejs.render(template,{}));
});
Note the use of readFileSync(). If you specify the encoding (utf8 here), the function returns a string containing your template.
注意使用readFileSync()。如果您指定编码(此处为 utf8),该函数将返回一个包含您的模板的字符串。
回答by Wtower
The answer of @ksloan should be the accepted one. It uses the ejs function precisely for this purpose.
@ksloan 的答案应该是公认的。它正是为此目的使用 ejs 函数。
Here is an example of how to use with Bluebird:
以下是如何与 Bluebird 一起使用的示例:
var Promise = require('bluebird');
var path = require('path');
var ejs = Promise.promisifyAll(require('ejs'));
ejs.renderFileAsync(path.join(__dirname, 'template.ejs'), {context: 'my context'})
.then(function (tpl) {
console.log(tpl);
})
.catch(function (error) {
console.log(error);
});
For the sake of completeness here is a promisified version of the currently accepted answer:
为了完整起见,这里是当前接受的答案的承诺版本:
var ejs = require('ejs');
var Promise = require('bluebird');
var fs = Promise.promisifyAll(require('fs'));
var path = require('path');
fs.readFileAsync(path.join(__dirname, 'template.ejs'), 'utf-8')
.then(function (tpl) {
console.log(ejs.render(tpl, {context: 'my context'}));
})
.catch(function (error) {
console.log(error);
});
回答by Kartik Malik
@ksloan's answer is really good. I also had the same use case and did little bit of digging. The function renderFile() is overloaded. The one you will need mostly is:
@ ksloan的回答真的很好。我也有相同的用例,并做了一些挖掘。函数 renderFile() 被重载。您最需要的是:
renderFile(path: string,data, cb)
for example:
例如:
ejs.renderFile(__dirname + '/template.ejs', dataForTemplate, function(err, data) {
console.log(err || data)
})
where dataForTemplateis an object containing values that you need inside the template.
其中dataForTemplate是一个包含模板中所需值的对象。
回答by Ankur Mahajan
Use ejs.renderFile(filename, data)function with async-await.
将ejs.renderFile(filename, data)函数与async-await 一起使用。
To render HTML files.
呈现 HTML 文件。
const renderHtmlFile = async () => {
try {
//Parameters inside the HTML file
let params = {firstName : 'John', lastName: 'Doe'};
let html = await ejs.renderFile(__dirname + '/template.html', params);
console.log(html);
} catch (error) {
console.log("Error occured: ", error);
}
}
To render EJS files.
渲染 EJS 文件。
const renderEjsFile = async () => {
try {
//Parameters inside the HTML file
let params = {firstName : 'John', lastName: 'Doe'};
let ejs = await ejs.renderFile(__dirname + '/template.ejs', params);
console.log(ejs);
} catch (error) {
console.log("Error occured: ", error);
}
}

