简体   繁体   中英

How can I use ternary operator in ejs?

  <% kindOfDay === "Saturday" || kindOfDay === "Sunday" ? { %>
  <h1 style="color: purple;"><%= kindOfDay %> List</h1>
  <% } : { %>
  <h1 style="color: blue;"><%= kindOfDay %> List</h1>
  <% } %>

I want to use ternary operator in ejs so i wrote this code in.ejs file. But it didn't work. Should I only use if-else in ejs?

The ternary operator creates a single expression and does not use { } .

It is used like condition? a: b condition? a: b or condition? (a): (b) condition? (a): (b) not condition? {a}: {b} condition? {a}: {b} .

If/else on the other hand, is used with curly braces like if (condition) {a} else {b}


However in your case, you can simplify your code to:

<h1 style="color: <%= (kindOfDay === "Saturday" || kindOfDay === "Sunday") ? "purple" : "blue" %>"><%= kindOfDay %> List</h1>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM