2012-11-23 92 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/*' 
          } 
         );