Skip to content

Instantly share code, notes, and snippets.

@kinglozzer
Created September 6, 2019 09:43
Show Gist options
  • Save kinglozzer/246bf69e157bf07d8b4b4520d0cbe8d5 to your computer and use it in GitHub Desktop.
Save kinglozzer/246bf69e157bf07d8b4b4520d0cbe8d5 to your computer and use it in GitHub Desktop.
Responsive CMS videos
<?php
use App\View\Shortcodes\EmbedShortcodeProvider;
use SilverStripe\View\Parsers\ShortcodeParser;
ShortcodeParser::get('default')
->register('embed', [EmbedShortcodeProvider::class, 'handle_shortcode']);
.typography {
.responsive-video {
max-width: 100%;
// padding-bottom will be added by JavaScript
&.responsive-ready {
position: relative;
height: 0;
iframe {
position: absolute;
top: 0; left: 0;
width: 100%; height: 100%;
}
}
}
}
import $ from 'jquery';
$(() => {
$('.responsive-video').each((i, elem) => {
const $elem = $(elem);
const $iframe = $elem.find('iframe');
if (!$iframe.length) {
return;
}
const padding = ($iframe.height() / $iframe.width() * 100);
$elem.css('padding-bottom', `${padding}%`);
$elem.addClass('responsive-ready');
});
});
<?php
namespace App\View\Shortcodes;
use SilverStripe\Core\Convert;
use SilverStripe\View\HTML;
use SilverStripe\View\Parsers\ShortcodeHandler;
use SilverStripe\View\Shortcodes\EmbedShortcodeProvider as SilverStripeEmbedShortcodeProvider;
/**
* Overrides the built-in embed shortcode provider so we can create adjust
* the HTML to create responsive video embeds
*/
class EmbedShortcodeProvider extends SilverStripeEmbedShortcodeProvider implements ShortcodeHandler
{
protected static function videoEmbed($arguments, $content): string
{
// Convert caption to <p>
if (!empty($arguments['caption'])) {
$xmlCaption = Convert::raw2xml($arguments['caption']);
$content .= "\n<p class=\"caption\">{$xmlCaption}</p>";
}
$html = HTML::createTag('div', ['class' => 'responsive-video'], $content);
if (!empty($arguments['width'])) {
$arguments['style'] = 'width: ' . intval($arguments['width']) . 'px;';
}
unset($arguments['width'], $arguments['height'], $arguments['url'], $arguments['caption']);
return HTML::createTag('div', $arguments, $html);
}
public static function embedForTemplate($embed, $arguments): ?string
{
switch ($embed->getType()) {
case 'video':
case 'rich':
// Attempt to inherit width (but leave height auto)
if (empty($arguments['width']) && $embed->getWidth()) {
$arguments['width'] = $embed->getWidth();
}
return static::videoEmbed($arguments, $embed->getCode());
case 'link':
return static::linkEmbed($arguments, $embed->getUrl(), $embed->getTitle());
case 'photo':
return static::photoEmbed($arguments, $embed->getUrl());
default:
return null;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment