Drupal 8: get language prefix

  • Posted on: 5 December 2017
  • By: Darko

Language prefix is user configurable, for example you can set it to null for default language or to be different from the language code.

http://mysite.com/admin/config/regional/language/detection/url

If you need to get a language prefix in you code, in Drupal 8, this is how to do it:

  function getLanguagePrefix() {
    if($prefixes = Drupal::config('language.negotiation')->get('url.prefixes')) {
      $language = Drupal::languageManager()->getCurrentLanguage()->getId();
      if($prefixes[$language]){
        return "/" . $prefixes[$language];
      }
    return null;
  }