Recently i had to add a custom svg icon per menu item. These icons were not in fontawesome or some other icon library. I had to add a span before the title so i could show them per menu item. This is how i did it.
use Drupal\Component\Render\FormattableMarkup;
/**
* Implements hook_preprocess_hook().
*
* @inheritdoc
*/
function customTheme_preprocess_menu(&$variables) {
if (isset($variables['menu_name']) && $variables['menu_name'] === 'main') {
foreach($variables['items'] as $key => $item) {
$variables['items'][$key]['title'] = new FormattableMarkup('<span class="icon-block"> </span><span>@title</span>', [
'@title' => $variables['items'][$key]['title'],
]);
}
}
}
Do not forget to add the namespace
use Drupal\Component\Render\FormattableMarkup;