0
votes

I'm making a small Node web app using Express. But I get errors if my ejs files contain else statements. If that's not clear, here's an MWE:

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

If I then try to visit localhost:5000/test, I see only this error message:

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)

But if I delete the <% else {foo = "z"} %> line, everything works perfectly! What gives?

2

2 Answers

3
votes

This should work for you

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

or if you need it in separate lines

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

You can try and compile the template from a standalone script:

const ejs = require('ejs');

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

With the debug option set, you can see what the template gets compiled to:

  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("");

Notice how ; __append() is inserted between the if and the else line, breaking the the syntax of if () { ... } else { ... }.

For a solution, I'll defer to the answer posted by @ponury-kostek.