0

I am creating a multilingual D8 site, which 3 languages enabled.

In trying to display the currently active language, the snippet

$lang = \Drupal::languageManager()->getCurrentLanguage()->getName();

always returns the default language ( English ) even though the UI has switched to one of the alternative languages. The above line is called from the mytheme.theme file in hook_preprocess_page.

In the language switcher block, the correct language is getting the session-active is-active classes.

When referencing the documentation for D8.5 in the above method, in the code shown it very much shows like this is what the function does:

public function getCurrentLanguage($type = LanguageInterface::TYPE_INTERFACE) 
{
  return $this
    ->getDefaultLanguage();
}

Am I missing something obvious here? Is there another way to get the current active language?

  • 1
    What are your language detection/selection settings for both content and interface? getCurrentLanguage will return the current interface (not content) language unless you pass it LanguageInterface::TYPE_CONTENT, and depending on your settings, interface language might not be being detected the same way as content language – Clive Aug 28 '18 at 12:26
2

The method you've quoted is the default code for single language sites. For multilingual sites the default LanguageManager is replaced with ConfigurableLanguageManager and the method is overridden wtih this content:

ConfigurableLanguageManager::getCurrentLanguage:

public function getCurrentLanguage($type = LanguageInterface::TYPE_INTERFACE) {
  if (!isset($this->negotiatedLanguages[$type])) {

    // Ensure we have a valid value for this language type.
    $this->negotiatedLanguages[$type] = $this
      ->getDefaultLanguage();
    if ($this->negotiator && $this
      ->isMultilingual()) {
      if (!$this->initializing) {
        $this->initializing = TRUE;
        $negotiation = $this->negotiator
          ->initializeType($type);
        $this->negotiatedLanguages[$type] = reset($negotiation);
        $this->negotiatedMethods[$type] = key($negotiation);
        $this->initializing = FALSE;
      }
      elseif ($type == LanguageInterface::TYPE_INTERFACE) {
        return new Language([
          'id' => LanguageInterface::LANGCODE_SYSTEM,
        ]);
      }
    }
  }
  return $this->negotiatedLanguages[$type];
}

Then the result depends on the language negotiators you have configured in language detection, see comment from @Clive.

|improve this answer|||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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