webc icon indicating copy to clipboard operation
webc copied to clipboard

Conditional boolean attributes

Open bennypowers opened this issue 1 year ago • 8 comments

Consider this lit-html template

html`<a href="${ifDefined(href)}"></a>`;

if href is undefined, the output will be:

<a></a>

Why is this important?

Consider

<script webc:for="script of scripts"
      :defer="script.defer"
      :async="script.async"
      :src="url(script.src)"></script>

In this case, all scripts will be async and defer because those are boolean attributes whose presence indicates true.

If we wanted to use a template and ifs:

<template webc:nokeep webc:for="script of scripts">
  <script webc:if="defer && async" defer async :src="url(script.src)"></script>
  <script webc:elseif="defer" defer            :src="url(script.src)"></script>
  <script webc:elseif="async" async            :src="url(script.src)"></script>
  <script webc:else                            :src="url(script.src)"></script>
</template>

I guess that's ok? If you have lots of attrs, you have to keep track of a whole tree of if/then/else.

But what if null meant "remove this attribute"?:

<script webc:for="script of scripts"
       :defer="script.defer ?? null"
       :async="script.async ?? null"
       :src="url(script.src)"></script>

bennypowers avatar Apr 03 '23 15:04 bennypowers