I have a content type article which have a field repeatable "related content"

I use a field twig where I have this loop

{% for item in items %}
    {{ item.content }}
{% endfor %}

It works very well : it displays title of the article and a link to the content.

I would like also to display some subfields associated with this content but I'm not successful.

I’ve tried things like :

{{ item.content.field_date_mise_a_jour_article.value }}

but obviously it doesn’t work. item.content only contains url and title.

How can I do that ?

In node--article.html.twig, i can access the related content subfield like that :

{{ node.field_suggestion_articles.entity.field_date_mise_a_jour_article.value }}

How can I do the same in

  • You can user preprocess functions for this and write your code in hook_preprocess_field and there you can create a custom variable to be used in field twig. Did your try this ? Dec 19 '17 at 11:38
  • @MohitWadhwa No, i didn’t try (I was hoping to access custom fields directly in twig template.) but i’ve seen some topics here on this approach. I will try. Maybe you have some code to start ? Dec 19 '17 at 11:41
  • You can access the node in a field twig as well, {% set node = element['#object'] %}, and use the node the same way as in a node template.
    – 4k4
    Dec 19 '17 at 11:54
  • @4k4 How do you do ? I've also found your answer here drupal.stackexchange.com/questions/233977/… which helps me with {{ item.content['#node'].field_name.value }} Dec 19 '17 at 12:03
  • 1
    BTW digging too deep in the template variables is a sign that you need a custom view mode of the referenced entity. Then you can configure the fields in UI and if still necessary theme a view mode specific template (use Twig debug to find this out).
    – 4k4
    Dec 19 '17 at 12:33

As you are creating the twig template for a field and try to access the fields / data that is not available, you can write your custom code in preprocess function and you should use the template_preproces_field and create custom variable with desired data and use that variable in custom twig template.

In preprocess function

$variables['myVariable'] = 'My Desired Data';

In Twig use the variable which will print 'My Desired Data'

{{ myVariable }}

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.