Put an HTML non breaking space ( ) in menu items titles

Last updated on
3 November 2020

Drupal 7 will no longer be supported after January 5, 2025. Learn more and find resources for Drupal 7 sites

Adding HTML like   to menu titles can be helpful when you want to prevent menu titles which contain spaces from automatically wrapping to another line based on the position of a space character in the title. For example, for a menu title of "Reorder Images", depending on your layout, Drupal may put a line break between the word "Reoder" and the word "Images". Putting the code below into your template.php and changing the title to "Reorder Images", prevents this line break from happening.

Add this to your template.php:

function YOURTHEMENAME_link($variables) {
$variables['options']['html'] = TRUE;
  return '<a href="' . check_plain(url($variables['path'], $variables['options'])) . '"' . drupal_attributes($variables['options']['attributes']) . '>' . ($variables['options']['html'] ? $variables['text'] : check_plain($variables['text'])) . '</a>';
}

replace YOURTHEMENAME with your theme name.
This is Drupal 7 core function theme_link() and I just added option $variables['options']['html'] = TRUE; and that's it.

Acknowledgement to xalexas comment at https://www.drupal.org/node/112352#comment-9976285 for this helpful tip.

For Drupal 8 you can write this :

use Drupal\Core\Render\Markup;

/**
 * Implements hook_preprocess_HOOK()
 */
function YOURTHEME_preprocess_menu(&$variables){
  foreach($variables['items'] as &$link){
    $link['title'] = Markup::create($link['title']);
  }
}

Your link title must be a instance of MarkupInterface.

Help improve this page

Page status: No known problems

You can: