node.js ejs include error

Problem

I am creating this template:

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

But I always get this error:

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

Directories:

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

Can someone help, I according to toolbox everything should work

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

using ejs I render template, which constructs from other templates. Using ejs-locals it says that it has no method render. Is there any way to do this with only 'ejs' ??

Problem courtesy of: sauletasmiestas

Solution

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');
Solution courtesy of: Alex

Discussion

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

Discussion courtesy of: user2468356

This recipe can be found in it's original form on Stack Over Flow.