#optionally add attributes to HTML

3 messages · Page 1 of 1 (latest)

bright spire
#

Say I have some attributes I want to conditionally show on an element.

I cant do autoplay={false} because for HTML the fact that the attrivute is there at all , means it's true.

Would like the attribute to only be added it ift's true

<video
class:list={classList}
autoplay={autoplay}
loop="true"
playsinline
controls="false"
muted="true"
preload="auto"
width="640"
height="264"
data-setup="{}"

{/* If the link is an .m3u8 link, type="application/x-mpegURL" */}
{videoLink.includes('.m3u8') && <source src={videoLink} type="application/x-mpegURL" />}

{/* If the link is an .mp4 link, type="video/mp4" */}
{videoLink.includes('.mp4') && <source src={videoLink} type="video/mp4" />}

<p class="vjs-no-js">
    To view this video please enable JavaScript, and consider upgrading to a web browser that
    <a href="https://videojs.com/html5-video-support/" target="_blank">supports HTML5 video</a>
</p>

</video>

slim viperBOT
#

Hi @bright spire. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

You can conditionally include HTML attributes in Astro by using JavaScript expressions directly in the template. Attributes whose value evaluates to false, null, or undefined are omitted when rendered. [Template expressions]

So for boolean attributes like autoplay, do:

<video
  class:list={classList}
  autoplay={autoplay}   <!-- only rendered if autoplay is truthy -->
  loop
  playsinline
  controls={showControls}
  muted
  preload="auto"
  width="640"
  height="264"
  data-setup="{}"
>
  {videoLink.includes('.m3u8') && (
    <source src={videoLink} type="application/x-mpegURL" />
  )}
  {videoLink.includes('.mp4') && (
    <source src={videoLink} type="video/mp4" />
  )}

  <p class="vjs-no-js">
    To view this video please enable JavaScript, and consider upgrading to a web browser that
    <a href="<https://videojs.com/html5-video-support/"> target="_blank">
      supports HTML5 video
    </a>
  </p>
</video>

Key points:

  • autoplay={autoplay} will only output autoplay if autoplay is truthy; if false/undefined, the attribute is omitted. [Dynamic attributes]
  • For non-boolean attributes where you want "true" / "false" explicitly (e.g. data-*), pass true/false and Astro v5 will render ="true" / ="false". [Attribute values]

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: