Ternary operator in Pug syntax
Asked Answered
D

2

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!

Diestock answered 20/11, 2019 at 14:28 Comment(1)
try changing the variable name to a different thing other than disabled search on the Internet. #21492950 #52488922 it seems like it existsHanks
J
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>.

Jasisa answered 20/11, 2019 at 16:43 Comment(0)
D
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" />
Daze answered 20/11, 2019 at 20:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.