我需要在页面中显示svg图像。由于svg图像将使用css进行样式设置(如填充、笔划等属性),因此svg必须是内联的。现在我还需要设置类属性(<svg class="someClass">...</svg>
)这些svg文件是动态的。
现在,我的问题是页面可以动态加载任意数量的svg图像。类名都将从数组中加载。由于svg是内联的,因此不可能使用循环来填充类名。
所以我想用json来处理这个问题。
{
"icon-name-1" : {
"viewbox" : "0 0 100 100",
"svgContent" : "..."
},
"icon-name-2" : {
"viewbox" : "0 0 100 100",
"svgContent" : "..."
},
...
}
然后在PHP中,我将文件加载到一个json_对象中,并使用一个函数加载图标,最后循环数组(现在也有图标名)以回显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]);
}
我觉得我把事情搞得太复杂了。所以我想知道是否有更好的方法或其他方法达到同样的效果?但我喜欢的一点是,我不必在代码中看到任何内联svg,这肯定会是一场噩梦:)
最佳答案
事实上,这是一个过于复杂的病例。我所要做的就是在svg代码中使用一个类似于class={{class-name}}
的占位符,然后使用加载svg文件并使用一个简单的字符串替换来实现相同的目的。
$svg = file_get_contents($svgPath);
$svg = str_replace("{{class-name}}", $array[$index], $svg);
JSON完全没有意义。吸取了教训。