added svg_image() twig function

This commit is contained in:
Andy Miller
2020-08-25 14:47:17 -06:00
parent 55903dab11
commit 747b081809
2 changed files with 43 additions and 0 deletions

View File

@@ -1,3 +1,9 @@
# v1.7.0-rc.16
## mm/dd/2020
1. [](#new)
* Added a new `svg_image()` twig function to make it easier to 'include' SVG source in Twig
# v1.7.0-rc.15
## 07/22/2020

View File

@@ -187,6 +187,7 @@ class TwigExtension extends AbstractExtension implements GlobalsInterface
new TwigFunction('nicefilesize', [$this, 'niceFilesizeFunc']),
new TwigFunction('nicetime', [$this, 'nicetimeFunc']),
new TwigFunction('cron', [$this, 'cronFunc']),
new TwigFunction('svg_image', [$this, 'svgImageFunction']),
new TwigFunction('xss', [$this, 'xssFunc']),
@@ -1412,6 +1413,42 @@ class TwigExtension extends AbstractExtension implements GlobalsInterface
return $body_classes;
}
/**
* Returns the content of an SVG image and adds extra classes as needed
*
* @param $path
* @param $classes
* @return string|string[]|null
*/
public static function svgImageFunction($path, $classes)
{
$path = Utils::fullPath($path);
if (file_exists($path)) {
$svg = file_get_contents($path);
$classes = " inline-block $classes";
$matched = false;
//Look for existing class
$svg = preg_replace_callback('/^<svg.*?(class=\"(.*?)").*>/', function($matches) use ($classes, &$matched) {
if (isset($matches[2])) {
$new_classes = $matches[2] . $classes;
$matched = true;
return str_replace($matches[1], "class=\"$new_classes\"", $matches[0]);
}
}, $svg
);
// no matches found just add the class
if (!$matched) {
$classes = trim($classes);
$svg = str_replace('<svg ', "<svg class=\"$classes\" ", $svg);
}
return $svg;
}
}
/**
* Dump/Encode data into YAML format