Reputation: 119
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!
Upvotes: 6
Views: 6088
Reputation: 7802
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>
.
Upvotes: 6
Reputation: 8031
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" />
Upvotes: 3