3

I have been trying to figure out how I can pull the url of a node content type using an entity reference.

enter image description here

Apparently using {{ links.entity.uri }} or {{ links.entity.url }} does not work

<div>

{% for links in node.field_related_items %}

    <h2>{{ links.entity.label }}</h2>
    <a href="{{ links.entity.uri }} " ></a>

{% endfor %}

</div>
clestcruz
  • 1,081
  • 3
  • 31
  • 75

1 Answers1

2

This worked for me:

<a href="{{ links.entity.id }}"></a>

This will only take you to /node/entity_id though and not /entity_name/entity_id

I would like to expand upon this answer by saying that you should add a Drupal::entityQuery() to your .theme file. Inside of this query, you'll want to grab the "alias" which is the link to the content. In your case this will give you these links /migrations and /aboutiom.

Here's an example of what that might look like...

  function theme_name_preprocess_node(&$variables) {
    $query = \Drupal::entityQuery('node')
                  ->condition('status', 1)
                  ->condition('type', 'related_links')
    $nids = $query->execute();
    $nodes =  \Drupal\node\Entity\Node::loadMultiple($nids);
    $related_links = [];
    foreach ($nodes as $item) {
      $alias = \Drupal::service('path.alias_manager')->getAliasByPath('/node/'.$item->id());
      $related_links[] = [
        'title' => $item->getTitle(),
        'id' => $item->id(),
        'field' => $item->get('field_name')->value,
        'alias' => $alias,
      ];
    }
    $variables['related_links'] = $related_links;
  }

Now in your twig template you can do something like this...

{% for link in related_links %}
    <a href="{{ link['alias'] }}">{{ link['title'] }}</a>
{% endfor %}
Jake Stewart
  • 143
  • 2
  • 12