Get current language in a template file 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()-&gt;getCurrentLanguage()-&gt;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()-&gt;getCurrentLanguage()-&gt;getId();
  }

  public function getFunctions() {
    return array (
      new \Twig_SimpleFunction('languagecheck', array($this, 'currentLang')),
    );
  } 
}
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(&amp;$variables) {
  $variables['attributes']['class'][] = 'clearfix';
}