node.js ejs包含错误

我正在创build这个模板:

<% include head %> <Placemark> <name><%=name%></name> <description><%=description%></description> <Point> <coordinates><%=coordinates%></coordinates> </Point> </Placemark> <% include foot %> 

但是我总是得到这个错误:

 if (!filename) throw new Error('filename option is required for includ ^ 

目录:

 justas@justas-Studio-1555:~/node-socket.io/socket.io/examples/kml$ ls -1 app.js foot.ejs head.ejs placemark.ejs 

有人可以帮忙,我根据工具箱的一切应该工作

app.js:

 var http = require('http'); var ejs = require('ejs'); var fs = require('fs') http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/xml'}); fs.readFile('placemark.ejs', 'utf8', function (err, template) { var content = ejs.render(template,{ name:"test name", description:"this is the description", coordinates:"-122.0822035425683,37.42228990140251,0" }); res.write(content); res.end() }); }).listen(8000); console.log('Server listening at at xxxxxxxx'); 

使用ejs我渲染模板,从其他模板构造。 用ejs-locals说它没有方法渲染。 有没有办法做到这一点只有'ejs'?

这是一个工作的例子:

看来你需要传递模板的文件名,以便能够使用include – 请参阅示例

 var http = require('http'); var ejs = require('ejs'); var fs = require('fs'); http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/xml'}); fs.readFile('placemark.ejs', 'utf8', function (err, template) { var content = ejs.render(template,{ name:"test name", description:"this is the description", coordinates:"-122.0822035425683,37.42228990140251,0", filename: __dirname + '/placemark.ejs' }); res.write(content); res.end() }); }).listen(8000); console.log('Server listening at at xxxxxxxx'); 

我最近也遇到了这个错误。 我看到alexjamesbrown的答案,但我不喜欢解决scheme。 我宁愿不包括每个渲染的文件名variables; 代码可能变得凌乱! 我宁愿将文件包含在各个视图中。

所以我挖入ejs的lib文件,并删除文件名variables的要求。

您将在第157行的\ ejs \ lib \ ejs.js中find以下内容

 if (!filename) throw new Error('filename option is required for includes'); 

只需注释掉该行,并在您的.ejs文件中使用<% include views\include.ejs %>即可包含您的各个视图。

以上对于ejs 0.8.4版本是有效的

刚刚碰到这个问题,这里是如何定义模板文件夹,并将这些模板包含在您的主要ejs文件中:

 var renderedHtml = ejs.render(content, { data: data, filename: __dirname + '/app/templates/*' } );