Skip to content

Instantly share code, notes, and snippets.

@Nemo64
Created July 17, 2014 07:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Nemo64/a9a636ae0c037f8b8458 to your computer and use it in GitHub Desktop.
Save Nemo64/a9a636ae0c037f8b8458 to your computer and use it in GitHub Desktop.
An Extbase ViewHelper which inlines svgs into the template
<?php
class SvgImportViewHelper extends \TYPO3\CMS\Fluid\Core\ViewHelper\AbstractViewHelper
{
private static $id = 0;
/**
* Renders the content.
*
* @param string $src
* @return string
* @api
*/
public function render($src) {
$content = file_get_contents(PATH_site . '/' . $src);
$content = preg_replace('/\\<\\?.*?\\?\\>\\s*/', '', $content); // remove xml annotation
$content = preg_replace('/\\<!DOCTYPE.*?\\>\\s*/', '', $content); // remove doctype annotation
$content = preg_replace('/\\<\\!--.*?--\\>\\s*/', '', $content); // remove comments
$content = preg_replace('/\\w+:\\S+=".*?"\\s*/', '', $content); // remove namespace attributes
$content = preg_replace('/\\<metadata[^\\>]*\\>.*?\\<\\/metadata\\>/s', '', $content); // remove metadata
$content = preg_replace('/\\<(\w+:\w+)[^\\>]*\\>.*?\\<\\/\\1\\>\\s*/s', '', $content); // remove namespace extensions
$content = preg_replace('/\\<(\w+:\w+)[^\\>]*\\/\\>\\s*/s', '', $content); // remove namespace extensions single tag
// convert style="" attributes
$content = preg_replace_callback('/style="(.*?)"/', function ($matches) {
$styles = preg_split('/\s*;\s*/', trim($matches[1]));
$attributes = array();
foreach ($styles as $style) {
list($name, $value) = preg_split('/\s*:\s*/', trim($style));
$attributes[] = "$name=\"$value\"";
}
return implode(' ', $attributes);
}, $content);
// prefix ids
$prefix = 'svg_' . (self::$id++) . '_';
$ids = array();
$content = preg_replace_callback('/id="(.*?)"/', function ($matches) use($prefix, &$ids) {
$ids[$matches[1]] = $prefix . $matches[1];
return $matches[0]; // don't change for now
}, $content);
$content = str_replace(array_keys($ids), array_values($ids), $content);
return $content;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment