node.js ejs include error

ⅰ亾dé卋堺 提交于 2019-12-04 07:15:28

Here is a working example:

It appears you need to pass in the filename of the template, in order to be able to use include - See example here

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');

I recently came across this error too. I saw alexjamesbrown's answer, but I did not like the solution. I would rather not be including the filename variable for every render; code can become messy! I would prefer to include the file inside the individual views.

So I dug into the ejs lib file and remove the requirement for the filename variable.

You will find the following in \ejs\lib\ejs.js on line 157

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

Simply comment out that line and use <% include views\include.ejs %> in your .ejs files to include your individual views.

The above is valid for ejs version 0.8.4

Just bumped into this question and here's how you can define a template folder and include those templates in your main ejs file:

var renderedHtml = ejs.render(content, 
                            {
                                data: data,
                                filename: __dirname + '/app/templates/*'
                            }
                        );
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!