2017-02-22 206 views
0

我正在使用快递小节点的Web应用程序。但是如果我的ejs文件包含else语句,我会得到错误。如果这是不明确的,这里是一个MWE:.ejs文件不渲染,如果它包含else语句

页/ 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"); 
}); 

如果我再尝试访问本地主机:5000 /测试,我只看到这个错误信息:

SyntaxError: Unexpected token else in C:\path\to\my\files\pages\test.ejs while compiling ejs

If the above error is not helpful, you may want to try EJS-Lint: https://github.com/RyanZim/EJS-Lint at new Function() at Template.compile (C:\path\to\my\files\node_modules\ejs\lib\ejs.js:524:12) at Object.compile (C:\path\to\my\files\node_modules\ejs\lib\ejs.js:338:16) at handleCache (C:\path\to\my\files\node_modules\ejs\lib\ejs.js:181:18) at tryHandleCache (C:\path\to\my\files\node_modules\ejs\lib\ejs.js:203:14) at View.exports.renderFile [as engine] (C:\path\to\my\files\node_modules\ejs\lib\ejs.js:412:10) at View.render (C:\path\to\my\files\node_modules\express\lib\view.js:126:8) at tryRender (C:\path\to\my\files\node_modules\express\lib\application.js:639:10) at Function.render (C:\path\to\my\files\node_modules\express\lib\application.js:591:3) at ServerResponse.render (C:\path\to\my\files\node_modules\express\lib\response.js:960:7)

但是,如果我删除<% else {foo = "z"} %>线,一切工作完美!是什么赋予了?

回答

1

这应该为你

<html> 
<head></head> 
<body> 
    <% var foo = "x"; %> 
    <% if (2==3) {foo = "y";} else {foo = "z";} %> 
    <%= foo %> 
</body> 
</html> 

工作,或者如果你需要在不同的行

<html> 
<head></head> 
<body> 
    <% var foo = "x"; %> 
    <% if (2==3) {foo = "y";} else { %> 
    <% foo = "z";} %> 
    <%= foo %> 
</body> 
</html> 
0

你可以尝试从独立脚本编译模板:

const ejs = require('ejs'); 

console.log(ejs.compile(` 
<html> 
    ... 
</html> 
`, { debug : true })); 

通过设置debug option,您可以看到模板编译到的内容:

var __output = [], __append = __output.push.bind(__output); 
    with (locals || {}) { 
    ; __append("\n<html>\n<head></head>\n<body>\n ") 
    ; var foo = "x"; 
    ; __append("\n ") 
    ; if (2==3) {foo = "y";} 
    ; __append("\n ") 
    ; else {foo = "z";} 
    ; __append("\n\n ") 
    ; __append(escapeFn(foo)) 
    ; __append("\n</body>\n</html>\n") 
    } 
    return __output.join(""); 

通知; __append()是如何插入ifelse线之间,打破了的if() { ... } else { ... }的语法。

解决的办法,我会听从张贴@ ponury-kostek答案。