6

Is it possible to use ternary operator in Pug code ?

My attempt to make it work:

Pug file

- var disabled = true
input(type="checkbox" disabled ? disabled : null)

HTML result

<input disabled ? disabled : null></input>

HTML desired result

<input disabled></input>

I know about standard conditional Pug syntax which described here, but it hard to believe that there's no chance of using ternary operator in modern Pug syntax.

Thanks for helping me!

Arsen
  • 119
  • 2
  • 7
  • try changing the variable name to a different thing other than **disabled** search on the Internet. https://stackoverflow.com/questions/21492450/jade-ternary-operator-add-element https://stackoverflow.com/questions/52488422/pugjs-able-to-use-ternary-for-text it seems like it exists – canbax Nov 20 '19 at 14:33

2 Answers2

6

You're very close - Pug just needs an attribute to start the processing. Your code was just doing an evaluation without belonging to any attribute.

So just add the attribute that you want evaluated up front then put the ternary operator after it. In this case you just want disabled to appear and nothing more, so let's use an empty string for true and null for false to let pug know what to do.

Here it is working in a codepen.

div
  - var disabled = true;
  input(disabled = disabled ? '' : null)

With true, pug generates <input disabled>.

With false, pug generates <input>.

Graham
  • 7,431
  • 18
  • 59
  • 84
3

In this case, if your variable is a boolean, you actually don't need to use a ternary operator. You can just assign the value to the attribute. Pug has a built-in system for handling boolean attributes, and even renders terse (non-mirrored) attributes if the doctype is html.

Pug:

- var foo = true
input(type='checkbox', disabled= foo)
- var bar = false
input(type='checkbox', disabled= bar)

Rendered HTML (if the doctype is html)

<input type="checkbox" disabled />
<input type="checkbox" />
Sean
  • 6,873
  • 4
  • 21
  • 46