首页 > 解决方案 > EJS 和条件语句

问题描述

请参阅下面的错误。我正在使用 EJS "^3.1.5" 和 express "^4.17.1" 和打字稿。为什么 EJS 不评估 else 分支?

ReferenceError: /home/pauld/tscript/dist/views/index.ejs:12
    10| </head>
    11| <body>
 >> 12| <%- include("./partials/nav"), {user: user} %>
    13|     <div class="container">
    14|         <h1 class="header">Header</h1>
    15|         <a class="btn" href="/start"><i class="material-icons right">arrow_forward</i>Get started!</a>

/home/pauld/tscript/dist/views/partials/nav.ejs:4
    2|     <div class="nav-wrapper">
    3|         <a href="/" class="brand-logo">
 >> 4|  <% if ( user ) { %>
    5|          <%= user.name %>'s 
    6|  <% } else { %>
    7|          Anonymous

user is not defined
at eval (/home/pauld/tscript/dist/views/partials/nav.ejs:12:8)
    at nav (/home/pauld/tscript/node_modules/ejs/lib/ejs.js:691:17)
    at include (/home/pauld/tscript/node_modules/ejs/lib/ejs.js:689:39)
    at eval (/home/pauld/tscript/dist/views/index.ejs:12:17)

更新:

如果我将每个 Russopotomus 的第 12 行更新为:

<%- include("./partials/nav", {user: user}) %>

然后我得到相同的错误,堆栈跟踪略有不同:

ReferenceError: /home/pauld/tscript/dist/views/index.ejs:12
    10| </head>
    11| <body>
 >> 12| <%- include("./partials/nav", {user: user}) %>
    13|     <div class="container">
    14|         <h1 class="header">Header</h1>
    15|         <a class="btn" href="/start"><i class="material-icons right">arrow_forward</i>Get started!</a>

user is not defined
    at eval (/home/pauld/tscript/dist/views/index.ejs:12:50)
    at index (/home/pauld/tscript/node_modules/ejs/lib/ejs.js:691:17)

...

换句话说,它不包括带有部分的位。

标签: node.jstypescriptexpresslogicejs

解决方案


此行不正确:

<%- include("./partials/nav"), {user: user} %>

您必须将渲染数据作为参数传递给包含函数调用:

<%- include("./partials/nav", {user: user}) %>

(如果不清楚 - 圆括号的位置)已更改)


推荐阅读