Given a random string, Is there a way to check if that is an available icon within the current Kirby setup (which can be used directy in an k-icon
html tag as type
), or if it should be tried as an emoji?
You can get all icons like this:
$svg = new SimpleXMLElement(F::read(kirby()->root('panel') . '/dist/img/icons.svg'));
$icons = [];
foreach ($svg->defs->children() as $symbol) {
array_push($icons, str_replace('icon-', '', $symbol->attributes()->id));
}
Then you can check with in_array("random-string", $icons)
if it exists.
Seems to work great.
For now cached it and made it a SiteMethod
getter.
Hopefully these things won’t hurt performance too much
Hey, sorry to digg this up and thanks for the directions here.
I took some time to wrap it in a cached plugin and added icons from plugins to the list.
<?php
// File: site/plugins/iconkit/index.php
// Original code from @bvdputte https://forum.getkirby.com/t/check-if-icon-exist/19734, which is a simplified version of https://github.com/getkirby/getkirby.com/blob/main/site/models/reference-icons.php
// Improved by @Daandelange to use cache, include additional plugin icons, a site method, and an isIcon validator
// MIT
Kirby::plugin('daandelange/iconkit', [
// Returns an array with all icon names, uses cache
// Usage: site()->kirbyIcons()
'kirbyIcons' => function(){
$cache = kirby()->cache('daandelange.iconkit');
$icons = $cache->get('icons');
// there's nothing in the cache, so let's fetch it
if ($icons === null) {
$icons = [];
// Get native kirby icons
$svg = new SimpleXMLElement(F::read(kirby()->root('panel') . '/dist/img/icons.svg'));
foreach ($svg->defs->children() as $symbol) {
array_push($icons, str_replace('icon-', '', $symbol->attributes()->id));
}
// Inject plugin icons
foreach(new Collection(kirby()->plugins()) as $key=>$pluginInfo){
if( array_key_exists('icons', $pluginInfo->extends()) ){
$pluginicons = array_keys($pluginInfo->extends()['icons']);
if(count($pluginicons)>0) $icons = array_merge($icons, $pluginicons);
}
}
// Store cache for next time
$cache->set('icons', $icons, 60*24*7); // Update cache once a week = ok ?
}
return $icons;
},
// Enable cache for this plugin
'options' => [
'cache' => true
],
// Custom validators
'validators' => [
// Validates icon names
// usage : V::isIcon('paint-brush')
'isIcon' => function ($value) {
return V::in($value, site()->kirbyIcons()); // or in_array($value, $icons);
},
],
// Plugin icons must be registered this way in the php plugin declaration file:
// Which is : /¡\ NOT AS DOCUMENTED /!\
//'icons' => [
// 'test-icon' => '', // Inject icon name for iconkit plugin
//]
]);