Skip to content

Instantly share code, notes, and snippets.

@rossriley
Last active December 12, 2017 16:16
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rossriley/ba14e8a336b56778991103952d8b55ad to your computer and use it in GitHub Desktop.
Save rossriley/ba14e8a336b56778991103952d8b55ad to your computer and use it in GitHub Desktop.
Twig Extension to replace files with thumbnails
<?php
namespace MyApp\Twig;
use Twig_Extension;
use Twig_SimpleFilter;
class TwigExtension extends Twig_Extension
{
public $app;
public function __construct($app)
{
$this->app = $app;
}
public function getName()
{
return 'myappTwig';
}
public function getFilters()
{
return [
new Twig_SimpleFilter('replace_thumbnails', [$this, 'replaceWithThumbnails']),
];
}
public function replaceWithThumbnails($text)
{
$doc = new DOMDocument('1.0', 'UTF-8');
$doc->strictErrorChecking = true;
$doc->standalone = true;
$doc->xmlStandalone = true;
$doc->formatOutput = true;
$doc->loadHTML($text, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
$allImageNodes = $doc->getElementsByTagName("img");
foreach($allImageNodes as $searchNode)
{
$src = $searchNode->getAttribute('src');
if (strpos($src, '/files/') !== false) {
$width = $searchNode->getAttribute('width') ?: 1000;
$height = $searchNode->getAttribute('height') ?: 1000;
$src = preg_replace('#(.*)(/files/)(.*)#', '$1/thumbs/'.$width.'x'.$height.'c/$3', $src);
$searchNode->setAttribute('src', $src);
$searchNode->removeAttribute('width');
$searchNode->removeAttribute('height');
$doc->importNode($searchNode);
}
}
return $doc->saveHTML();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment