This tutorial will guide you through editing a Drupal 11 Superfish menu item title programmatically to include HTML with a custom module. This will likely work with Drupal 8, 9, 10 and 11, but has only been tested on Drupal 11.
Create a Drupal custom module and/or add the following code to your custom_module.module file.
/**
* Implements hook_preprocess_HOOK() for superfish-menu-items.
*/
function custom_module_preprocess_superfish_menu_items(&$variables) {
// Loop through the menu items array and modify labels as needed.
foreach ($variables['menu_items'] as &$menu_item) {
// Check for a specific condition (e.g., the menu item's title or ID).
if ($menu_item["link"]["#title"]->__toString() === 'Old link text') {
// Modify the label of the menu item.
$menu_item["link"]["#title"] = t('New link text <i class="fa-solid fa-lock"></i>');
}
}
}
More information
- Drupal: Step by step tutorial: Hello World
- Drupal: Superfish Dropdown Menu
- Drupal: function FormattableMarkup::__toString
- Drupal: class FormattableMarkup