EJS 的三元运算符子句中的多行

Multiple lines in ternary operator clause with EJS

我正在尝试使用多行三元子句根据 currentUser 是否是 post 的所有者有条件地在页面上呈现不同的内容。

如果他们制作了 post,我想显示 edit/delete 按钮。如果他们不是所有者,我想显示 post 所有者的用户名。

我在 React 中遇到过类似的问题,直到我意识到我只需要投入一大堆 parens() 就可以让它工作。

这是我当前的 EJS 代码(格式或多或少与我使用 JSX 时的编写方式相同):

<% (currentUser && artpiece.author.id.equals(currentUser._id)) ? ( %>

   <a class='btn btn-warning btn-sm' href='/artpieces/<%= artpiece._id %>/edit'>Edit</a>
   <form style='display: inline' action="/artpieces/<%= artpiece._id %>?_method=DELETE" method="POST">
        <button class='btn btn-danger btn-sm' onclick="return confirm('Are you sure you want to delete this artpiece?')">Delete</button>
<% </form> ) : ( %>

<% <p><em>Submitted by <%= artpiece.author.username %></em></p> ) %>

提前致谢!

不能像 EJS 那样使用三元运算符。

虽然 JSX 直接编译成普通的旧 JavaScript,但 EJS 编译成中间字符串表示形式,但有更多的问题 including added semicolons。实际上,这意味着您只能在 JavaScript 接受分号前缀 的位置开始 EJS 标记,不幸的是,三元运算符与 EJS 添加分号的方式不符。如果在编译时启用调试,您可以看到生成的输出:

// EJS for an if else statement
ejs.compile(
  `<% if (true) { %>yes<% } else { %>no <% } %>`,
  { debug: true }
)

// Generated JS for evaluation
// Notice that each <% %> turns into a '    ; ' + line + '\n';
var __output = [], __append = __output.push.bind(__output);
with (locals || {}) {
  ;  if (true) { 
  ; __append("yes")
  ;  } else { 
  ; __append("no ")
  ;  } 
}

// EJS for a ternary statement
ejs.compile(
   `<% true ? ( %>yes<% ) : ( %>no <% ) %>`,
   { debug: true }
)

// Generated JS, again each <% %> turns into '    ; ' + line + '\n';
// but this time, the JavaScript generated is invalid.

var __output = [], __append = __output.push.bind(__output);
with (locals || {}) {
  ;  true ? ( 
  ; __append("yes")
  ;  ) : ( 
  ; __append("no ")
  ;  ) 
}
return __output.join("");

† JavaScript 在比预期更多的地方接受分号。例如,您可以在打开块的任何大括号之后放置一个分号,因为该分号将分隔空语句。

; if (true) {; console.log("it's true!"); };
; while (true) {; console.log("it's true!"); break; };
; function whaaat(a) {; console.log(`it's ${a}!`); };