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!