5

我正在创建这个模板:

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

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

应用程序.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'来做到这一点?

4

3 回答 3

10

这是一个工作示例:

看来您需要传入模板的文件名才能使用包含 - 请参见此处的示例

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');
于 2012-11-23T23:59:30.680 回答
3

我最近也遇到了这个错误。我看到了 alexjamesbrown 的回答,但我不喜欢这个解决方案。我宁愿不为每个渲染都包含文件名变量;代码可能会变得混乱!我更愿意将文件包含在单个视图中。

所以我深入研究了 ejs lib 文件并删除了对文件名变量的要求。

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

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

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

以上对ejs版本0.8.4有效

于 2013-06-09T13:41:19.633 回答
0

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

var renderedHtml = ejs.render(content, 
                            {
                                data: data,
                                filename: __dirname + '/app/templates/*'
                            }
                        );
于 2017-07-24T08:16:01.380 回答