0

I'm sorry for my bad English. In my node.html.twig I have two layouts for two groups of languages.

  1. English, Ukrainian and Bulgarian
  2. Arabic, Farsi, Urdu I can't check with twig which is the active language to load one of the two layouts. I tried this but it didn't work. Thanks a lot if anyone can help me
{% if language.getId() == 'en' or 'uk' or 'bg' or 'ru' %}

    
        {{ content.field_mt_srv_body }}
        {{ content.field_sp_working_hours }}
        {{ content.field_sp_additional_information }}
        {{ content.field_mt_srv_video }}
    
    
         {{ content.field_sp_street_view }}
     
       
  • {{ content.field_sp_city }}
  • {{ content.field_sp_address }}
  • {{ content.field_sp_email }}
  • {{ content.field_field_sp_phone }}
  • {{ content.field_sp_languages }}
  • {{ content.field_mt_srv_tags }}
  • {{ content.field_sp_website }}
  • {{ content.field_sp_facebook }}
  • {% else %} {{ content.field_mt_srv_body }} {{ content.field_sp_working_hours }} {{ content.field_sp_additional_information }} {{ content.field_mt_srv_video }} {{ content.field_sp_street_view }} {{ content.field_sp_city }} {{ content.field_sp_address }} {{ content.field_sp_email }} {{ content.field_field_sp_phone }} {{ content.field_sp_languages }} {{ content.field_mt_srv_tags }} {{ content.field_sp_website }} {{ content.field_sp_facebook }} {% endif %}

    2 Answers 2

    1

    To get this working in Twig

    {% if language.getId() == 'en' or 'uk' or 'bg' or 'ru' %}
    

    you have to define the variable language in a preprocess hook:

    mytheme.theme or mymodule.module

    /**
     * Implements hook_preprocess_HOOK() for node templates.
     */
    function mytheme/mymodule_preprocess_node(&$variables) {
      $variables['language'] = \Drupal::languageManager()->getCurrentLanguage();
    }
    

    The only template where this variable is predefined is the page template, so that you don't need the preprocess hook. See this core preprocess hook: https://api.drupal.org/api/drupal/core%21includes%21theme.inc/function/template_preprocess_page/

    -1

    In Drupal 8.5.7 and upwards a global variable 'language' exists that can be called directly in twig like example below.

    {% if language == 'en' %} 
    

    See this resource here

    1
    • 1
      This is incorrect, there is no global language in templates. It was only added to page.html.twig, but not other templates likes node.html.twig
      – Hudri
      Commented Oct 11, 2022 at 13:27

    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.