diff --git a/CHANGELOG.md b/CHANGELOG.md index 4aecc1d47..2a414878c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/system/src/Grav/Common/Twig/TwigExtension.php b/system/src/Grav/Common/Twig/TwigExtension.php index a0aada5e8..f05f502ec 100644 --- a/system/src/Grav/Common/Twig/TwigExtension.php +++ b/system/src/Grav/Common/Twig/TwigExtension.php @@ -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('/^/', 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('