Get entity reference node object from within rendered entity reference My specific problem is similar to the one here but I am needing for it to work when the file field is within a node that is rendered within another as an entity reference.

If I use:

$node = \Drupal::request()-&gt;attributes-&gt;get('node');
$variables['node_title'] = $node-&gt;getTitle();


I get the title of the main node currently being displayed and not the node of the rendered entity reference. Is there a way I can get this instead?
You're setting $node to the current request. On any node/* route that will be the node in question, not other nodes included on the page.

Since it is an entity reference field, you can access it like (for example, in a preprocess):

$foo_id = $node-&gt;field_reference_name-&gt;value;
$referenced_node = Node::load($foo_id);

// or
$referenced_file = File::load($foo_id);


If $node-&gt;field_name-&gt;value returns the id (node id).

However it isn't really clear if you are talking about a file, or, a node.