Skip to content

Instantly share code, notes, and snippets.

@zemd
Last active November 14, 2017 16:18
Show Gist options
  • Save zemd/926d8daee364d9fb63cf to your computer and use it in GitHub Desktop.
Save zemd/926d8daee364d9fb63cf to your computer and use it in GitHub Desktop.
Simple twig extension function that returns datauri string for given file
<?php
namespace AppBundle\Twig\Extension;
use Symfony\Component\HttpFoundation\File\File;
use Symfony\Component\HttpKernel\KernelInterface;
/**
* Usage example,
* <img src="{{ data_uri('@AcmeBundle/Resources/public/images/logo.svg') }}">
*/
class DataUriExtension extends \Twig_Extension
{
/** @var KernelInterface */
protected $kernel;
public function __construct(KernelInterface $kernel) {
$this->kernel = $kernel;
}
/**
* Returns the name of the extension.
*
* @return string The extension name
*/
public function getName() {
return 'base64';
}
/**
* {@inheritdoc}
*/
public function getFunctions() {
return [
new \Twig_SimpleFunction('data_uri', [$this, 'getDataUri'])
];
}
public function getDataUri($path) {
$realpath = $this->kernel->locateResource($path);
$file = new File($realpath, true);
$mimeType = $file->getMimeType();
$params = [];
$data = file_get_contents($realpath);
$isBinaryData = strpos($mimeType, 'text/') !== 0;
if (null === $mimeType) {
$mimeType = 'text/plain';
$parameters['charset'] = 'US-ASCII';
}
$parameters = '';
if (0 !== count($params)) {
foreach ($params as $paramName => $paramValue) {
$parameters .= sprintf(';%s=%s', $paramName, $paramValue);
}
}
$base64 = '';
if ($isBinaryData) {
$base64 = sprintf(';%s', 'base64');
$dataURI = base64_encode($data);
} else {
$dataURI = rawurlencode($data);
}
return sprintf('data:%s%s%s,%s', $mimeType, $parameters, $base64, $dataURI);
}
}
services:
app_datauri.twig_extension:
class: AppBundle\Twig\Extension\DataUriExtension
public: false
arguments: ["@kernel"]
tags:
- { name: twig.extension }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment