LoginSignup
3
0

More than 3 years have passed since last update.

EJSのif文でtrueの時だけ出力する。

Last updated at Posted at 2020-11-25

やりたいこと

<% const person = { name: 'taro' };%>
<% if (person.name) { %><%= person.name %><% } %>
  • 上記のような値があったときだけ出力する記述をスマートに書きたい。
  • <%が多いので減らしたい。

結論

以下のように書くと完結に書くことができます。

<%= person.name ? person.name : '' %>

三項演算子を使用します。偽値の場合は空文字です。

試したこと

<%= if(person.name) { person.name } %> // エラー
<%= if(person.name) person.name %> // エラー
<% if(person.name) person.name %>  // 出力されない

偽値を省略できていないのが心残りですが、
結論の<%= person.name ? person.name : '' %>がシンプル。

他にいい方法があったら教えてください :bow_tone1:

3
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
0