2012-11-23 91 views
5

我创建这个模板:node.js的EJS包括错误

<% 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 
         ^

目录:

[email protected]:~/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'来做到这一点?

+0

什么版本你正在使用ejs和express吗?这看起来是正确的,是我使用的。 https://github.com/visionmedia/ejs – chovy

+0

/home/justas ├──[email protected] ├─┬[email protected] – sauletasmiestas

回答

10

这里是一个工作示例:

看样子你需要在模板的文件名来传递,为了能够使用包括 - 见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'); 
+0

它无法识别“partial”ReferenceError:ejs:1 > > 1 | <% - partial('head')%> 2 | 3 | <%=name%> 4 | <%= description%> 部分未定义 ' – sauletasmiestas

+0

您是否在您的应用中使用require('ejs')? – Alex

+1

部分不支持最新的ejs和表达式3.您需要ejs-locals。 – chovy

3

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

因此,我深入到ejs库文件并删除了文件名变量的要求。

你会发现上线157

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

在\ EJS \ LIB \ ejs.js下面简单地注释掉该行并使用您的.ejs文件<% include views\include.ejs %>包括您个人的看法。

以上的有效期为EJS版本0.8.4

+0

哇,你太棒了,这很棒。我刚刚在github上添加了一个bug。https://github.com/visionmedia/ejs/issues/137 – JasonS

+0

干杯@JasonS - 只是为了更新这不再是行157.在ejs \ lib \ ejs.js文件中搜索此行。 – 2015-01-03 11:25:13

0

就撞上了这个问题,这里是你如何定义模板文件夹,并在您的主EJS文件这些模板:

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