In my case the noads are stored in three different languages. How can add a condition, where I specify the language for the title that need to be loaded?

foreach($references as $reference){
    if($node = Node::load($reference->nid)){
      $url = Url::fromRoute('entity.node.canonical', array('node' => $node->id()))->toString();
      $link = '<a href="'.$url.'">'.$this->t($node->getTitle()).'</a>';
      $render .= '<li>'.$link.'</li>';

Where $references is an array of nids.

  • 1
    In general, never use t() with user input (only as placeholders) as that could lead to security issues. Entities also have a toLink() method, wihch returns a Link object that has a toString(), so you can simplify your two lines to $node->getTranslation()->toLink()->toString(). There is also a links template, but it unfortunately doesn't work with Link objects, instead it expects a list of arrays with the keys title and url, which is an Url object that you can get with $node->toUrl(). – Berdir Sep 19 '18 at 9:33
  • 1
    And last, your $reference->nid object looks suspicously like a database query result. In case you are querying the node table, you should use an entity query instead. – Berdir Sep 19 '18 at 9:34

You can load the translation separately with ContentEntityBase::getTranslation, e.g.:

if ($node->hasTranslation('es')) {
  $translation = $node->getTranslation('es');
  $translated_title = $translation->label();

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.