Take the 2-minute tour ×
Craft CMS Stack Exchange is a question and answer site for administrators, end users, developers and designers for Craft CMS. It's 100% free, no registration required.

When using rich text fields, is there a way to automatically wrap embedded content (specifically, videos) in some kind of custom HTML?

I'd like to, at the very least, wrap the embed in some element (a <div>, for instance) with some kind of class or ID, so that it'd be something like <div class="inline-media">EMBED HERE</div>.

I've found my way to the Craft docs for rich text fields, and see that I may be able to add this functionality via Redactor, but I'm not sure how to go about doing so.

Any suggestions are appreciated.

share|improve this question

1 Answer 1

up vote 7 down vote accepted

I suggest a Twig filter so you can do something like this in the template:

{{ entry.body | wrapembeds }}

This is something to love about Craft - the ease of building Twig filters.

In the plugins directory create a folder videoembeds.

Create the main plugin file WrapEmbedsPlugin.php:

<?php
namespace Craft;

class WrapEmbedsPlugin extends BasePlugin
{
    public function getName()
    {
        return Craft::t('Embed Wrapper Twig Filter');
    }

    public function getVersion()
    {
        return '0.0';
    }

    public function getDeveloper()
    {
        return 'Your Name';
    }

    public function getDeveloperUrl()
    {
        return 'http://yoursite.com';
    }

    public function hookAddTwigExtension()
    {
        Craft::import('plugins.wrapembeds.WrapEmbedsTwigExtension');
        return new WrapEmbedsTwigExtension();
    }
}

Create another file WrapEmbedsTwigExtension.php:

<?php
namespace Craft;

class WrapEmbedsTwigExtension extends \Twig_Extension
{
  protected $env;

  public function getName()
  {
    return 'WrapEmbeds Twig Extension';
  }

  public function getFilters()
  {
    return array('wrapembeds' => new \Twig_Filter_Method($this, 'wrapembeds'));
  }

  public function initRuntime(\Twig_Environment $env)
  {
    $this->env = $env;
  }

  public function wrapembeds($content)
  {
    $filtered = preg_replace_callback('/<iframe.+iframe>/', function($matches) {
      return '<div class="inline-media">'. $matches[0] . '</div>';
    }, $content);

    $charset = craft()->templates->getTwig()->getCharset();
    $filtered = new RichTextData($filtered, $charset);

    return $filtered;
  }

}

Enable the plugin in the admin then add the filter to the template tag. Hopefully this is enough to get you started adding custom Twig filters. Simple once you know how and very handy!

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.