1

I am looking for a solution to add "optional chaining" on PugJS to set data-active="true" if i === 0.

Bellow is my current code. This code is working, but the problem with this approach (bellow) is that I have to repeat my code on a else statement and that doesn't make sense. I have to add (i === 0 ? 'data-active="true"' : '') on the .my__element, but I don't know how to do it.

if (i === 0)
  .my__element(data-month=months[month] data-active="true")
else
  .my__element(data-month=months[month])

Any help please? Thank you

Nuno Marques
  • 155
  • 1
  • 10

1 Answers1

3

Attribute values in Pug are "just regular JavaScript," as mentioned on the Attributes page on Pug docs.

If an attribute's value is false, Pug doesn't print the attribute at all. This can be seen in the Boolean Attributes section on the same page:

// Input (Pug):
input(type='checkbox' checked)
input(type='checkbox' checked=true)
input(type='checkbox' checked=false)
input(type='checkbox' checked="true")

// Output (HTML):
<input type="checkbox" checked="checked" />
<input type="checkbox" checked="checked" />
<input type="checkbox" />
<input type="checkbox" checked="true" />

So, you can use i === 0 && "true" as the value for the data-active attribute:

.my__element(data-month=months[month] data-active=(i === 0 && "true"))

The parentheses around the attribute's value are optional, but they improve readability. So this is OK but less readable:

.my__element(data-month=months[month] data-active=i === 0 && "true")

A more verbose alternative:

.my__element(data-month=months[month] data-active=(i === 0 ? "true" : false))
.my__element(data-month=months[month] data-active=i === 0 ? "true" : false)

(Note that "true" is a string and false is a boolean; this is on purpose. You can try to switch their types to see why.)

Matias Kinnunen
  • 7,828
  • 3
  • 35
  • 46
  • I've to say sometimes I go on the PugJS docs and it's hard to find exactly what we need. I see we have to look to the docs with a more surgical eye. Thank you for the whole explanation and for giving the "A more verbose alternative" example. – Nuno Marques Oct 04 '21 at 12:39