Though ideally if we use the views correctly and override them well, Drupal Views itself take care of getting the translated version as per configurations of the view. For details check this: EntityField::getValue
But if somehow we wanna get translated version of the entity in a views twig, we will have to get the current language and then call ContentEntityBase::getTranslation on the entity of the views row. And there are various ways of getting the current language in the views-view.html.twig:
#1 Use preprocess to add current language
function MYTHEME_preprocess_views_view(&$vars) {
$language = \Drupal::languageManager()->getCurrentLanguage()->getId();
$vars['language'] = $language;
}
#2 Use Bamboo Twig module:
{% set language = bamboo_i18n_current_lang() %}
And then call getTranslation on the entity, like:
row.content['#row']._entity.getTranslation(language)
Additionally, you can add a check of hasTranslation as well, if needed:
{% if row.content['#row']._entity.hastranslation(language) %}
This will do the job for you, but as recommended we should override twigs in a manner that we make use of Drupal Views way of getting entity field values which are translated based on what you configure in your views, if you remember views allow you to configure rendering language of current row. Overriding this way basically neglects those settings and renders in active language.
Apart from this method, there is also another way of doing it, which is just via preprocessing, but this might become complicated, as we will have to send array of translated results / rows of view separately:
$entity = \Drupal::service('entity.repository')->getTranslationFromContext($row->_entity);
Comments