1

I tried to get the current language in the menu.html.twig template file.

The current language is not available in this template and a preprocess function is not existing for this template as far as I could see. So I did not manage to get the current language by using template_preprocess function as it is described here.

I tried a few things but ended up creating my own Twig function that delivers \Drupal::languageManager()->getCurrentLanguage()->getId() in this (and any other) template.

I could think of declaring a global variable maybe in template_preprocess(), but I believe this is not a good option if I only want it in one special template.

So my question is: Is it a proper way for this to go via own TWIG function or is there another more easier way of doing this?

For reference I used code like this:

class MyLanguageCheckerExtension extends \Twig_Extension {

  public function getName()
  {
      return 'lang_check';
  }

  public function currentLang() {      

    return \Drupal::languageManager()->getCurrentLanguage()->getId();
  }

  public function getFunctions() {
    return array (
      new \Twig_SimpleFunction('languagecheck', array($this, 'currentLang')),
    );
  } 
}
2
  • Just curious, why do you need do a lang check? When you specify a menu you can select a language for this menu. So create a menu for each lang in the UI, if you need, and style them with proper template.
    – Vagner
    Nov 4, 2016 at 19:23
  • Yes separate menu for each language is good Option, but i intended to use only one menu and add a special item directly to the menu list dependent on the current language Nov 4, 2016 at 19:35

1 Answer 1

1

The proper way is in a preprocess function and this does exist for the menu template. The reason is caching. In the preprocess function you can check if the caching metadata is in synch with the additional information you add to the twig.

In case of the language, you might get this working in a Twig function, because many templates are already cache dependent on the language, but not with other information like (for example) information from the current user.

This is an example for the menu preprocess function from the Bartik theme.

/**
 * Implements hook_preprocess_HOOK() for menu.html.twig.
 */
function bartik_preprocess_menu(&$variables) {
  $variables['attributes']['class'][] = 'clearfix';
}
0

Your Answer

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

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