I know that the question has been asked several time but I didn't find how to get the translation of a node entity.

Here is the code :

    $countries = \Drupal::entityTypeManager()

    return [
      '#theme' => 'country_selector_block',
      '#langcode' => $lang->getId(),
      '#countries' => $countries,

And in the twig template I put :

{% for country in countries %}
    <option value="{{ country.field_code.value }}">{{ country.title.value|t }}</option>
{% endfor %}

=> but it return the country name in the default language

Can you explain how to handle that ?


You need to pass the loaded nodes/countries through the following so that Drupal marks the best available translation as active, then do not use t() in the template. That is a security risk, you must never pass user input to t().

$country = \Drupal::service('entity.repository')->getTranslationFromContext($country).

Do that in a loop on $countries for example, or use array_walk()/array_map().

  • So this is not possible to translate without making a foreach or array_walk/map ? Thank you for your answer ç
    – injetkilo
    Feb 15 '18 at 15:54
  • You need to call that method on each node/country somehow, so no.
    – Berdir
    Feb 15 '18 at 16:34
  • Ok thanks and in which hook should I apply this logic ? I tried in theme_preprocess_node() but things like links and content var are not translated :/
    – injetkilo
    Feb 19 '18 at 14:51
  • Well, in your own code, right between your two existing calls? Not sure why you talk about hook_preprocess_node() now
    – Berdir
    Feb 19 '18 at 20:35

You can add to the properties array the language that you want like this:

$properties = [
 'type' => 'article',
 'langcode' => 'es',

$countries = \Drupal::entityTypeManager()
  • That will filter the list on nodes that have an es translation but it will still load them with their default translation being active. See my answer. This is only needed if you want to additionally filter it to countries that are translated.
    – Berdir
    Feb 15 '18 at 7:26
  • @Berdir you're right, I misread the question. Feb 15 '18 at 15:18

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.