Could we help you? Please click the banners. We are young and desperately need the money
In modern web development, icons play a crucial role in enhancing user interfaces, improving accessibility, and conveying meaning in a visually appealing manner. One popular approach to incorporating icons into web projects is by utilizing icon fonts like IcoMoon. However, writing out the entire HTML structure required for these icons can be time-consuming. In this article, we'll explore a PHP helper function that simplifies the process of generating HTML for IcoMoon icons using an IcoMoon selection.json file.
A selection.js file comes with your generated IcoMoon font pack:
If you're missing the file, you you can simply regenerate your IcoMoon pack.
<?php
function icomoon($name, $classes = '') {
static $selection = null;
if (!$selection) {
$selection_json_path = 'path/to/selection';
if (!file_exists($selection_json_path)) {
throw new Exception("Icomoon appears to be missing or in an unusual location.");
}
$selection = json_decode(
file_get_contents($selection_json_path)
);
}
$icon_prefix = $selection->preferences->fontPref->prefix;
$path_count = 0;
foreach ($selection->icons as $icon) {
if ($icon->properties->name === $name) {
if (isset($icon->properties->code) && !empty($icon->properties->code)) {
$path_count = 1;
if (isset($icon->properties->codes)) {
$path_count = count($icon->properties->codes);
}
}
break;
}
}
if (1 > $path_count) {
throw new UnexpectedValueException("Unknown icon ({$name})");
}
$handle = $icon_prefix . $name;
ob_start();
?>
<span class="<?= $handle ?> icomoon-icon <?= $classes ?>">
<?php
if ($path_count > 1) {
foreach (range(1, $path_count) as $index) {
?>
<span class="path<?= $index ?>"></span>
<?php
}
}
?>
</span>
<?php
return ob_get_clean();
}
?>
Let's break down the key components of this helper function:
Here's how you can use the icomoon() function in your PHP projects:
<?php
echo icomoon('name', 'custom-class');
?>
Replace 'name' with the name of the desired icon from your Icomoon selection, and 'custom-class' with any additional CSS classes you want to apply. Mind that the name excludes the icon prefix.