Drupal - Get current language in template
I found my answer and post it here so maybe it helps others later.
First, in MYTHEME.theme
:
In Drupal 8.2 language got added to page the variables in template_preprocess_page. But in my current version 8.1 it didn't exist so I added it with:
function MYTHEME_preprocess_page(&$vars) {
$language = \Drupal::languageManager()->getCurrentLanguage()->getId();
$vars['language'] = $language;
}
Then in my Twig file I use {{ language }}
. Also I can get the language name with {{ language.getName() }}
.
Update
After Drupal 8.2 a global variable language
exists and now there's no more need to add it first.
{% if language.getId() == 'en' %}
Do something
{% else %}
Do something else
{% endif %}
Update Thanks @Lucas for his comment
on Drupal > 8.7.5
{% if language.getId() == 'en' %} should be {% if language == 'en' %}
On Drupal version 8.2.3 the language
variable is already available in Twig templates. A usage example is this:
{% if language.getId() == 'en' %}
Do something
{% else %}
Do something else
{% endif %}
{{ language }}
works but only in page
context.
The example of this question(page--front.html.twig
) happens to be a working one.
I tried in 8.7.6 with Xdebug. When called from somewhere other than page.html.twig
it will returns a null
instead of {Drupal\Core\Language\Language}
I think that's why some people report it working but others not. You might use it under node.html.twig
or something. In this case you still need to provide that under preprocess() function of your theme.