4

In Drupal 7 the current language is a global variable we can access with

global $language;
$langcode = $language->language; 

I want to know how can we access the current language in a Twig file in Drupal 8 (in page--front.html.twig for example)?

13

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 %}
  • Does not work. Drupal 8.3.7 here and {{ dump(language) }} gives me null. Note that I am in a twig in a module and not a theme. – Guillaume Bois Sep 14 '17 at 15:44
  • @GuillaumeBois I'm having the same issue, language variable is accessible inside the theme templates but not in my custom module template. Could you find anything? – madpoet Oct 8 '17 at 11:18
  • This simply does not work when trying to access the variable in the TWIG template. Works fine in the preprocess though. – John Cogan Feb 12 '18 at 17:03
  • Works in 8.5, just use {{ language.getId() }} in page.html.twig to print the language id – Hans Rossel May 6 '18 at 18:09
10

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 %}
  • Doesnt look like it. – Anil Maharjan Jan 24 at 16:46
  • From @Yusef's answer following is missing.. function MYTHEME_preprocess_page(&$vars) { $language = \Drupal::languageManager()->getCurrentLanguage()->getId(); $vars['language'] = $language; } – Anil Maharjan Jan 24 at 16:56
-2
<?php if($language->language == 'regional') { $lang = "tamil"; } else { $lang = "english"; } ?>
  • in drupal 8 twig file !!! – Yusef Mohamadi Jun 16 '16 at 7:33
  • @zhilevan, did u try to print $language variable? Is that empty? – ARUN Jun 16 '16 at 8:03
  • @ARUN I ask in drupal 8, in drupal 8 variables with $ not exists in twig file. – Yusef Mohamadi Jun 16 '16 at 8:09
  • @zhilevan, but template_preprocess_page function already passing language in to the template. – ARUN Jun 16 '16 at 8:14
  • @ARUN it added in 8.2 but I am using 8.1 :D – Yusef Mohamadi Jun 16 '16 at 8:22

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.