0

How can I get the user's current language code in a view as a raw value, for example en or fr-ca?

This isn't for filtering content. I need the raw value of the users' current language to pass into a URL for a third-party tool. I added a custom text field. Then placed in some Twig code. The code is just failing to the fallback else value.

Based on other forum posts, I tried this code.

{% if language.getId() == 'en' %}
  en
{% elseif language.getId() == 'es-us' %}
  es-us
{% elseif language.getId() == 'en-us' %}
  en-us
{% else %}
  failed
{% endif %}

I get failed.

{% if language == 'en' %} 
  en
{% elseif language == 'es-us' %}
  es-us
{% elseif language == 'en-us' %}
  en-us
{% else %}
  failed
{% endif %}

I still get failed.

{% if language.id() == 'en' %}
  en
{% elseif language.id() == 'es-us' %}
  es-us
{% elseif language.id() == 'en-us' %}
  en-us
{% else %}
  failed
{% endif %}

I still get the same output.

5
  • Does this answer your question? Get current language in template
    – leymannx
    Dec 13, 2019 at 18:17
  • When you say "User's current language code", do you mean the "current interface language" or a language that the user has selected on their profile?
    – CG Monroe
    Dec 13, 2019 at 20:33
  • @leymannx - unfortunately, no. That is the post I referenced for the above code attempts.
    – turpentyne
    Dec 13, 2019 at 21:28
  • @CG Monroe - I am attempting to get 'current interface language'
    – turpentyne
    Dec 13, 2019 at 21:28
  • You need two things, a current language token, see drupal.org/project/token_language and a views field handler supporting tokens, see drupal.stackexchange.com/a/259541/47547
    – 4uk4
    Dec 13, 2019 at 21:40

1 Answer 1

0

I would suggest adding a custom text field then add the language value as a field. this way you will have the language as a replacement pattern that you can use with any custom link field which would be something like {{ language }}

You need to checkout the style settings of to use the custom link option.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.