Html::tag helper with options

Im using html::tag helper to generate an HTML5 video player. I want to tie the muted, autoplay and controls options into toggle feilds. This are are just single options on the tag, they are not key/value pairs like ordinary attributes, but i have had to set them as true to make it work with the tag helper.

I could of course turn it into plain html and do what i want but i was wondering if there was a way to add those attributes based on toggle field values and use the tag helper?

heres the relevant line in my snipper:

$vidtag = Html::tag('video', [$videsourcetag], ['poster' => $posterurl, 'muted' => 'true', 'autoplay' => 'true', 'controls' => 'true', 'preload' => 'auto', 'class' => 'vidplayer']);

Hi James! What exactly doesn’t work as expected?

The options array on the helper is expecting key value pairs, so i cant do:

$vidtag = Html::tag('video', [], ['poster' => $posterurl, 'muted' => 'true', ($page->controls()->toBool()) ? 'controls' : '', 'preload' => 'auto', 'class' => 'vidplayer']);

Because that outputs 0=controls and i just need it to be controls;

I have done it the long way round but would rather use the helper since it easier to read and less lines of code.

<figure class="vidplayercontainer">
  <video class="vidplayer"
      <?= ($page->controls()->toBool()) ? 'controls' : ''; ?>
      <?= ($page->muted()->toBool()) ? 'muted' : ''; ?>
      <?= ($page->autoplay()->toBool()) ? 'autoplay' : ''; ?>
      src="<?= $videourl ?>"
      poster="<?= $posterurl ?>">
      <a href="<?= $videourl ?>">
        <img src="<?= $videourl ?>" alt="<?= $posteralt ?>">
      </a>
  </video>
</figure> 
$options = [
  'poster' => $posterurl,
  'class'  => 'vidplayer',
];
$page->controls()->toBool() ? $options['controls'] = 'true' : null;
// etc.

$vidtag = Html::tag('video', [$videsourcetag], $options);

Thanks, that worked… heres the final snippet:

<?php

$options = [
  'poster' => $posterurl,
  'class'  => 'vidplayer',
];

$page->controls()->toBool() ? $options['controls'] = 'true' : null;
$page->autoplay()->toBool() ? $options['autoplay'] = 'true' : null;
$page->muted()->toBool() ? $options['muted'] = 'true' : null;

$posterimage = Html::tag('img', null, ['src' => $posterurl, 'alt' => $posteralt]);
$videsourcetag = Html::tag('source', null, ['src' => $videourl, 'type' => $mime]);
$videsourcetag .= Html::tag('a', [$posterimage], ['href' => $videourl]);
$vidtag = Html::tag('video', [$videsourcetag], $options);
$player = Html::tag('figure', [$vidtag], ['class' => 'vidplayercontainer']);

echo $player
?>

This will also work and is probably better:

$options = [
	'poster'   => $posterurl,
	'controls' => $page->controls()->toBool() ? 'true' : null,

];
1 Like