3

I have a site with two languages, but it's pointless to show the name of the currently selected language in the language switcher block. How can I hide it?

3 Answers 3

5

The links generated by the Language API are alterable via hook_language_switch_links_alter(), so you can do this:

/**
 * Implements hook_language_switch_links_alter().
 */
function MYMODULE_language_switch_links_alter(array &$links, $type, $path) {
  global $language;

  unset($links[$language->language]);
}
1

A cleaner way is to do the following:

use Drupal\Core\Language\LanguageInterface;
use Drupal\Core\Url;

/**
 * Implements hook_language_switch_links_alter().
 */
function MYMODULE_general_language_switch_links_alter(array &$links, $type, Url $url): void {
  $current_language = \Drupal::languageManager()->getCurrentLanguage();
  
  // Make sure the language is instance of language interface.
  if (!$current_language instanceof LanguageInterface) {
    return;
  }
  
  // Make sure the language option exists.
  if (isset($links[$current_language->getId()])) {
    unset($links[$current_language->getId()]);
  }
}
0

[Drupal 8]:

Implement hook_language_switch_links_alter in a custom module like this:

 /**
 * Perform alterations on language switcher links.
 *
 * A language switcher link may need to point to a different path or use a
 * translated link text before going through the link generator, which will
 * just handle the path aliases.
 *
 * @param array $links
 *   Nested array of links keyed by language code.
 * @param string $type
 *   The language type the links will switch.
 * @param \Drupal\Core\Url $url
 *   The URL the switch links will be relative to.
 */
function hook_language_switch_links_alter(array &$links, $type, \Drupal\Core\Url $url) {
  $language_interface = \Drupal::languageManager()->getCurrentLanguage();
  $current_language_id = $language_interface->getId();
  unset($links[$current_language_id]);
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.