2017-02-22 1 views
0

Expressを使用して小さなNode Webアプリケーションを作成しています。しかし、ejsファイルにelse文が含まれているとエラーになります。私は、localhostを訪問しようとした場合else文が含まれていると.ejsファイルがレンダリングされない

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 /テストを、私は、

ページ/ 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ことがはっきりしない場合は、こちらをMWEです

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()if() { ... } else { ... }の構文を壊し、ifelse線との間に挿入されているかに注意してください。

解決策として、@ ponury-kostekが投稿した回答を延期します。

関連する問題