Search code examples
htmlternarytemplate-literals

How to make a true/false ternary operator simpler in a HTML template?


Below a partial html template of mine; I find it quite ugly...
Is there a way to make ${dod.city === true ? true : false} ternary simpler?
I couldn't find any way online.
Thanks a lot.

  <span data-desktop=${dod.city === true ? true : false} data-mobile=${dom.city === true ? true : false}>CITY</span>
  <span data-desktop=${dod.zipcode === true ? true : false} data-mobile=${dom.zipcode === true ? true : false}>ZIPCODE</span>
  <span data-desktop=${dod.building === true ? true : false} data-mobile=${dom.building === true ? true : false}>BUILDING</span>   

Solution

  • If you only wanted to pass true or false in data-desktop and data-mobile then you can do something like this:-

    <span data-desktop=${!!dod.city} data-mobile=${!!dom.city>CITY</span>
      <span data-desktop=${!!dod.zipcode} data-mobile=${!!dom.zipcode}>ZIPCODE</span>
      <span data-desktop=${!!dod.building} data-mobile=${!!dom.building}>BUILDING</span>