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')),
);
}
}