I need to display svg images in my page. Since the svg images will be styled (properties like fill, stroke etc) with css, so the svg has to be inline. Now I also need to set the class attribute ( <svg class="someClass">...</svg>
. ) of these svg files dynamically.
Now, my problem is the page can load any number of svg images dynamically. And the class names will all be loaded from an array. As the svg is inline, using a loop to fill the class names is impossible.
So I thought of using json to handle this.
{
"icon-name-1" : {
"viewbox" : "0 0 100 100",
"svgContent" : "..."
},
"icon-name-2" : {
"viewbox" : "0 0 100 100",
"svgContent" : "..."
},
...
}
Then in PHP, I loaded the file to a json_object and use a function to load the icon and finally looping the array, now with the icon names also, to echo the svg.
$iconObj = json_decode(file_get_contents("icons.json"));
function load_SVG ($iconObj, $iconName, $svgClassName) {
$viewbox = $iconObj->viewbox;
$svg = "<svg class='$svgClassName' viewBox='$viewbox'>";
$svg .= $iconObj->$iconName->svgContent;
$svg .= "</svg>";
return $svg;
}
// array is generated dynamically too
$arr = [
["class-name-1", "icon-name-1"],
["class-name-2", "icon-name-2"],
...
];
foreach ($arr as $item) {
load_SVG($iconObj, $item[0], $item[1]);
}
I am getting the feeling I am over-complicating things here. So I'd like to know if there is better way or another way of achieving the same? But one thing I like about this is I don't have to see any inline svg in the code which, for sure, would have been a nightmare :)