Score:0

Access (none related) entities from within twig without preprocessing

in flag

Within a nodes Twig template I am able to access e.g. referenced fields with...

{{ node.field_my_entity_reference.0.entity.field_my_field.0.value }}

With the help of Twig Tweak I am able to render fields from specific nodes by referencing their NID (here NID 1)...

{{ drupal_field('field_my_field', 'node', 1) }}

Now is it possible to directly access the fields of specific nodes by their NID, not just getting the rendered content, either by a way Drupal already provides or with the help of a module like Twig Tweak? I know this is possible through preprocessing, but I'm searching for a way to do this directly in Twig.

Score:1
ve flag

Drupal twig prevents you from a few functions, but you can add custom functionality via a custom twig extension, let's say get_any_node_field_value

in twig:

<div>
  {{get_any_node_field_value(nodeId, 'field_my_custom_name')}}
</div>

This article appears to give a good introduction into setting up a custom twig extension. In a nutshell:

web/modules/custom/your_module/src/Extension/TwigExtension.php:

<?php

namespace Drupal\your_module\Extension;

use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;

class TwigExtension extends AbstractExtension {

  public function getFunctions(): array {
    return [
      new TwigFunction('get_any_node_field_value', [$this, 'get_any_node_field_value']),
    ];


    public function get_any_node_field_value ($nodeId, $fieldName) {
      // your logic goes here  
    }

}

Please keep in mind, that this does not effect your cache settings, so you will not get automatic template updates, if the unrelated node X changed. Depending on your usecase this might not be an issue, but it might fall on your toes later. If you need to care about caching, it's better to go via the preprocess and extend also the cache tags.

ru flag
Betting 10 bucks this **will** fall on your toes later :-)
ve flag
Depends on the usecase I'd say - but I agree: It definitely has the potential to do so ;-)
4uk4 avatar
cn flag
It's no problem to write Twig functions with cache metadata or attachments. Just bubble them up. It's the same for all nested content, no matter if in a Twig function or not. They all run in the same render context.
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.