Created
February 24, 2023 09:54
-
-
Save danielstgt/8a8b6d510d9b5251495714d84e82dc6c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<template> | |
<svg> | |
<use :href="symbolId" /> | |
</svg> | |
</template> | |
<script> | |
export default { | |
props: ['icon'], | |
data() { | |
return { | |
symbolId: '#' + this.icon.replace(new RegExp('.'.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, '\\$1'), 'g'), '/') | |
} | |
} | |
} | |
</script> |
Author
danielstgt
commented
Feb 24, 2023
•
PHP SVG Symbol Sprite Generation
@php
if (! app()->isProduction()) {
cache()->forget('svg-dom');
}
cache()->rememberForever('svg-dom', function () {
function getDirContents($dir, &$results = []) {
$files = scandir($dir);
foreach ($files as $key => $value) {
if (str_starts_with($value, '.') || str_starts_with($value, '..')) {
continue;
}
$path = realpath($dir . DIRECTORY_SEPARATOR . $value);
if (is_dir($path)) {
getDirContents($path, $results);
} else if (str_ends_with($path, '.svg')) {
$subPath = substr($path, strlen(resource_path('svg/')));
$result = substr($subPath, 0, strlen($subPath) - strlen('.svg'));
$results[] = $result;
}
}
return $results;
}
$svgFiles = getDirContents(resource_path('svg'));
$svgResults = [];
foreach ($svgFiles as $svgFile) {
$svgResults[$svgFile] = file_get_contents(resource_path('svg/') . $svgFile . '.svg');
}
$symbols = [];
foreach ($svgResults as $id => $svg) {
$svg = trim($svg);
$svg = substr($svg, strlen('<svg'));
$svg = substr($svg, 0, strlen($svg) - strlen('svg>'));
$svg = '<symbol id="' . $id . '"' . $svg;
$svg = $svg . 'symbol>';
$symbols[$id] = $svg;
}
$svgOpening = '<svg id="__svg_symbols__" xmlns="http://www.w3.org/2000/svg" xmlns:link="http://www.w3.org/1999/xlink" style="position: absolute; width: 0px; height: 0px;">';
$svgClosing = '</svg>';
$svgSymbolsString = '';
foreach ($symbols as $symbol) {
$svgSymbolsString .= $symbol;
}
$svgDom = $svgOpening . $svgSymbolsString . $svgClosing;
return $svgDom;
});
@endphp
{!! cache('svg-dom') !!}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment