我正在使用Express创建一个小型的Node web应用程序 . 但是如果我的ejs文件包含else语句,我会收到错误 . 如果不清楚,这是一个MWE:
页/ test.ejs:
<html>
<head></head>
<body>
<% var foo = "x"; %>
<% if (2==3) {foo = "y";} %>
<% else {foo = "z";} //If I delete this line, everything works %>
<%= foo %>
</body>
</html>
index.js:
var express = require('express');
var app = express();
app.set('port', (process.env.PORT || 5000));
app.set('views', __dirname + '/pages');
app.set('view engine', 'ejs');
app.get('/test/', function(request, response) {
response.render("test");
});
如果我然后尝试访问localhost:5000 / test,我只看到此错误消息:
SyntaxError:编译ejs时C:\ path \ to \ my \ files \ pages \ test.ejs中的意外的令牌意外如果上述错误没有帮助,您可能想尝试EJS-Lint:https://github.com / RyanZim / EJS-Lint位于Object.compile(C:\ path)的Template.compile(C:\ path \ to \ my \ files \ node_modules \ ejs \ lib \ ejs.js:524:12)中的新Function() \ to \ my \ files \ node_modules \ ejs \ lib \ ejs.js:338:16)在handleCache(C:\ path \ to \ my \ files \ node_modules \ ejs \ lib \ ejs.js:181:18)at at View.exports.renderFile [作为引擎]的tryHandleCache(C:\ path \ to \ my \ files \ node_modules \ ejs \ lib \ ejs.js:203:14)(C:\ path \ to \ my \ files \ node_modules) \ ejs \ lib \ ejs.js:412:10)在try.render(C:\ path \ to \ my \ files \ node_modules \ express \ lib \ view.js:126:8)的tryRender(C:\ path) \ to \ my \ files \ node_modules \ express \ lib \ application.js:639:10)在Function.render(C:\ path \ to \ my \ files \ node_modules \ express \ lib \ application.js:591:3) )在ServerResponse.render(C:\ path \ to \ my \ files \ node_modules \ express \ lib \ response.js:960:7)
但如果我删除 <% else {foo = "z"} %>
行,一切都很完美!是什么赋予了?
2 回答
这应该适合你
或者如果您需要在单独的行中
您可以尝试从独立脚本编译模板:
使用debug option集,您可以看到模板编译到的内容:
注意如何在
if
和else
行之间插入; __append()
,打破了if () { ... } else { ... }
的语法 .对于解决方案,我将按照@ ponury-kostek发布的答案推荐 .