'Drupal 8 and Twig get language
i want to get the actual language which is chosen on a drupal 8 site in a node and start an if-request when e.g. the language is "en" to put out some content.
this is what i've already tried:
{% global language %}
{% set lang_name = language %}
{{ lang_name }}
and
{{ app.session.locale }}
{{ app.request.locale }}
but it doesnt work. can someone give me a hint how i can get the language via twig on drupal 8 or is this not possible at all?
Solution 1:[1]
In your XXX.theme file:
function XXX_preprocess_node(&$variables) {
$language = \Drupal::languageManager()->getCurrentLanguage()->getId();
$variables['language'] = $language;
}
in your node template:
{{ language }}
Solution 2:[2]
I think you need to set $language in php before using {% global language %} in twig:
$language = \Drupal::languageManager()->getCurrentLanguage()->getId();
Solution 3:[3]
For language id you can use:
{{ language.getId() }}
For language name:
{{ language.getName() }}
For example:
{% if language.getId() == 'sr' %}
<p>Zdravo svete!</p>
{% elseif language.getId() == 'hu' %}
<p>Helló világ!</p>
{% else %}
<p>Hello world!</p>
{% endif %}
Solution 4:[4]
For taxonomy terms you can do this:
{{ term.langcode.langcode }}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Frank Drebin |
| Solution 2 | spiilmusic |
| Solution 3 | Santo Boldizar |
| Solution 4 | cirrus3d |
