How to get node url from Entity Reference field? We have an ECK Bundle that has an Entity Reference to Article and Basic Page content type. In the twig template we are using the following line below to get the node's nid value and then using that in the twig template to create a link to that node. However, we are getting the following error message while logged out (for logged in users it works fine). 

How can we get the node's url for both anonymous and logged in users?

Twig template (eck-entity--component--eck-ref-node--default.html.twig where eck-ref-node is the eck bundle name):

{% set field = entity.field_eck_ref %}
{% set ref_node = field.0['#node'] %}
{% set nodeId = ref_node.nid.value %}
{% set nodeURL = path('entity.node.canonical', {'node': nodeId}) %}

&lt;a href={{ nodeUrl }}&gt;
...
&lt;/a&gt;


Error:


  Uncaught PHP Exception
  Symfony\Component\Routing\Exception\InvalidParameterException:
  "Parameter "node" for route "entity.node.canonical" must match "\d+"
  ("" given) to generate a corresponding URL."
#node is usually part of a render array. Don't know why you named this entity. If it were a real entity object, then you could get the node id directly with .target_id instead of ['#node'].

The problem with keys in render arrays like #node is, they are only included if needed for rendering, so it's not a good idea to write code which fails if it does not exist.

You have to look for the entity object. According to the template doc the entity is named eck_entity:

{#
/**
 * @file
 * Default theme implementation to display an ECK entity.
 *
 * Available variables:
 * - eck_entity: The full ECK entity with limited access to object properties
 *   and methods. Only "getter" methods (method names starting with "get",
 *   "has", or "is") and a few common methods such as "id" and "label" are
 *   available. Calling other methods (such as node.delete) will result in an
 *   exception.
 * - content: All ECK entity items. Use {{ content }} to print them all,
 *   or print a subset such as {{ content.field_example }}. Use
 *   {{ content|without('field_example') }} to temporarily suppress the printing
 *   of a given child element.
 * - attributes: HTML attributes for the containing element.
 *
 * @see template_preprocess_eck_entity()
 *
 * @ingroup themeable
 */
#}


If this is the template you use, then try something like this to access the field object and the target id of the node:

{% set field = eck_entity.field_eck_ref %}
{% set nodeId = field.0.target_id %}


This works independently of user permissions.

And only build the url when you are sure you have a node id, because otherwise your code still fails if the field is empty.