首页 文章

.ejs文件如果包含else语句则不呈现

提问于
浏览
0

我正在使用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 回答

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

    注意如何在 ifelse 行之间插入 ; __append() ,打破了 if () { ... } else { ... } 的语法 .

    对于解决方案,我将按照@ ponury-kostek发布的答案推荐 .

相关问题