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 :)
Indeed this was a case of over-complication. All I had to do was use a placeholder like class={{class-name}} in the svg code and then use load the svg file and use a simple string substitution to achieve the same.
$svg = file_get_contents($svgPath);
$svg = str_replace("{{class-name}}", $array[$index], $svg);
The JSON was complete pointless. Lesson learned.
I would say yes. Considering you are doing dynamically, wouldn't it be better to simply replace the class tags, or insert them, via JQuery or javascript? They give you excellent tools to mark all dynamically created tags.
{<ul>
<li><a href="#">Link 1</a></li>
<li><a href="#">Link 2</a></li>
<li><a href="#">Link 3</a></li>
</ul>
$( "content" ).each( function( index, element ){
console.log( $( this ).text() );
});}
naturally you would have to alter your debugging info into a class altering method instead of just debugging the text.
After reading the comments, I will provide an alternate answer, but I won't claim credit for this.
Someone else answered this question: Is there a better way to write HTML strings in PHP?
The suggestion I would go for is at the bottom of the thread.