5

I am trying to render fields from an entity reference in a twig template but they are displaying in the default language instead of the selected one. My twig code:

{% for location in node.field_locations %}
  <div class="home-location">
    <div class="wording">
      {{ location.entity.title.value }}
       <span>{{ location.entity.field_sub_title.value }}</span>
     </div>
   </div>
 {% endfor %}
1
  • which module you are using for language translation
    – user59414
    Mar 14, 2018 at 5:27

1 Answer 1

7

You can use the following procedure for translated fields

Add language in your THEMENAME.theme

function dru8_preprocess_node(&$vars) {
  $language = \Drupal::languageManager()->getCurrentLanguage()->getId();
  $vars['lang'] = $language;
}

And in your node.html.twig to get translated fields

{% if node.field_stories.entity.hastranslation(lang) %}
  <p>{{ node.field_stories.entity.translation(lang).title.value }}</p>
{% else %}
  <p>No translation<p/>
{% endif %}

Thus in your case you will need

{% for location in node.field_locations %}
  <div class="home-location">
    <div class="wording">
      {{ location.entity.translation(lang).title.value }}
       <span>{{ location.entity.translation(lang).field_sub_title.value }}</span>
     </div>
   </div>
 {% endfor %}
2
  • 2
    Thanks, that's very useful. But I'm disappointed that we have to put so much work in when it was so easy to use entity_metadata_wrapper in D7 !
    – Chris
    Mar 15, 2018 at 5:58
  • Ridiculousy helpful. The amount of digging through Twig templates it took to uncover this was nuts. Drupal's default node, paragraph, and field templates must do this automatically, but once you start overriding, use .entity at your peril if you have a multi-lingual site. Also, instead of using a pre-processor, you should be able to inspect the parent entity and get its language before you call the entity function on it. In the example above, it may be something like node.field_stories.0['#node'].langcode (or just node.langcode if you're confident it will cascade down). Dec 3, 2021 at 17:47

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.