Checking for translation in a Drupal 8/9 node template

Not so long ago, I encountered the following problem - on a site with Drupal 8, translated fields were no longer displayed in a certain type of content. Initially, there was an idea - to manually make a condition on the ID of the active language and display the translated value of the fields for this language, but if the translation is not set for the node in principle, then it will simply knock out an error. It turned out to be a slightly different solution - first, in the template, check for the translation of the ID for the node as a whole and only then display the values. How to get a language ID in a template, we discussed in one of the articles earlier.

{% if node.hastranslation(language) %}
    {% for items in node.field_punkt %}
        <div class="pretty_block">
            <div class="names">
                {{ items.entity.translation(language).field_titles.value }}
            </div>
        </div>
    {% endfor %}
{% endif %}

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.
The comment language code.