You can access single value field in node template easily:

{{ content.field_test }}
or
{{ node.field_test.value }}

But iteration over multiple value fields is not pretty:

{% for key, item in content.field_tags if key|first != '#' %}
  <div class="item-{{ key + 1 }}">{{ item }}</div>
{% endfor %}

You can, of course, use a field template, but sometimes it doesn't make sense to have a ton of field template when you can simply have one node template.

Example:

I need to add "," between a field's values (a multiple value entity references field rendered in label). So I have a field template with:

{% for item in items %}
  {{ item.content }}{% if not loop.last %},{% endif %}
{% endfor %}

And in my node template I have:

{% if content.field_facilities is not empty %}
   <p>{{ content.field_facilities }}</p>
{% endif %}

But I would prefer to have a similar code directly in my node template like:

{% if content.field_facilities is not empty %}
   <p>
     {# This do not works! #}
     {% for item in content.field_facilities %}
       {{ item.content }}{% if not loop.last %},{% endif %}
     {% endfor %}
   </p>
{% endif %}

What would be the best way to solve that?

See also:

Issue fork drupal-2776307

Command icon Show commands

Start within a Git clone of the project using the version control instructions.

Or, if you do not have SSH keys set up on git.drupalcode.org:

Comments

gagarine created an issue. See original summary.

gagarine’s picture

Issue summary: View changes
gagarine’s picture

Issue summary: View changes
gagarine’s picture

Issue summary: View changes
gagarine’s picture

The problem is mainly with entity reference.

One solution would be to create a twig filter passing the value to Element::children

That will then be somethings like

{% for item in content.field_tags|children %}
  <p>{{ item }}</p>
{% endfor %}

Version: 8.2.x-dev » 8.3.x-dev

Drupal 8.2.0-beta1 was released on August 3, 2016, which means new developments and disruptive changes should now be targeted against the 8.3.x-dev branch. For more information see the Drupal 8 minor version schedule and the Allowed changes during the Drupal 8 release cycle.

Version: 8.3.x-dev » 8.4.x-dev

Drupal 8.3.0-alpha1 will be released the week of January 30, 2017, which means new developments and disruptive changes should now be targeted against the 8.4.x-dev branch. For more information see the Drupal 8 minor version schedule and the Allowed changes during the Drupal 8 release cycle.

mezitlab’s picture

Regarding Gagarin's answer, here is the code of the Twig filter that I simply put in a custom module.

mymodule/mymodule.services.yml

services:
  mymodule.twig_extension:
    arguments: ['@renderer']
    class: Drupal\mymodule\TwigExtension\Children
    tags:
      - { name: twig.extension }

mymodule/src/TwigExtension/Children.php

namespace Drupal\mymodule\TwigExtension;


class Children extends \Twig_Extension
{

  /**
   * Generates a list of all Twig filters that this extension defines.
   */
  public function getFilters()
  {
    return [
      new \Twig_SimpleFilter('children', array($this, 'children')),
    ];
  }


  /**
   * Gets a unique identifier for this Twig extension.
   */
  public function getName()
  {
    return 'mymodule.twig_extension';
  }


  /**
   * Get the children of a field (FieldItemList)
   */
  public static function Children($variable)
  {
    if (!empty($variable['#items'])
      && $variable['#items']->count() > 0
    ) {
      return $variable['#items']->getIterator();
    }

    return null;
  }

}

in the Twig template (it will result a plain-text output):

  {% for item in content.field_tags|children %}
    {{ item.get('value').getValue() }}
  {% endfor %}

Version: 8.4.x-dev » 8.5.x-dev

Drupal 8.4.0-alpha1 will be released the week of July 31, 2017, which means new developments and disruptive changes should now be targeted against the 8.5.x-dev branch. For more information see the Drupal 8 minor version schedule and the Allowed changes during the Drupal 8 release cycle.

webcultist’s picture

As a front guy I can say, I already needed and still need this! Don't know how much time I already wasted on workarounds...

dawehner’s picture

As a first step it would be nice to add this to https://www.drupal.org/project/twig_extensions or https://www.drupal.org/project/twig_tweak
Allowing people to have access to it as soon is possible is a nice feature.

anybody’s picture

Yes this would be very useful in core or first in one of these helper modules. We're having that problems with paragraphs... ugly workaround.

pranali.addweb’s picture

We can find the solution to this problem by different types of approaches:

1. I am explaining this an example. Like if we are having an array named testArray from the controller to a twig template and want to print every element.

{% for element in testArray %}
        {{ element.someString }}, 
    {% endfor %} 

    <!--  output: 'test1, test2, test3, ' -->

2.

{{ myArray|join(', ') }}

    <!--  output: 'test1, test2, test3, ' -->

3. Another option to do it by this code

    {% for role in user.roles %}
        {{ role.name }}
        {% if not loop.last %},{% endif %}
    {% endfor %}

Hope this helps you.

Version: 8.5.x-dev » 8.6.x-dev

Drupal 8.5.0-alpha1 will be released the week of January 17, 2018, which means new developments and disruptive changes should now be targeted against the 8.6.x-dev branch. For more information see the Drupal 8 minor version schedule and the Allowed changes during the Drupal 8 release cycle.

Version: 8.6.x-dev » 8.7.x-dev

Drupal 8.6.0-alpha1 will be released the week of July 16, 2018, which means new developments and disruptive changes should now be targeted against the 8.7.x-dev branch. For more information see the Drupal 8 minor version schedule and the Allowed changes during the Drupal 8 release cycle.

jeroent’s picture

Status: Active » Needs review
Issue tags: +DX (Developer Experience)
StatusFileSize
new1.91 KB

The patch attached adds a twig filter based on the code in the twig_extender module.

https://cgit.drupalcode.org/twig_extender/tree/modules/twig_extender_ext...

Version: 8.7.x-dev » 8.8.x-dev

Drupal 8.7.0-alpha1 will be released the week of March 11, 2019, which means new developments and disruptive changes should now be targeted against the 8.8.x-dev branch. For more information see the Drupal 8 minor version schedule and the Allowed changes during the Drupal 8 release cycle.

Version: 8.8.x-dev » 8.9.x-dev

Drupal 8.8.0-alpha1 will be released the week of October 14th, 2019, which means new developments and disruptive changes should now be targeted against the 8.9.x-dev branch. (Any changes to 8.9.x will also be committed to 9.0.x in preparation for Drupal 9’s release, but some changes like significant feature additions will be deferred to 9.1.x.). For more information see the Drupal 8 and 9 minor version schedule and the Allowed changes during the Drupal 8 and 9 release cycles.

Version: 8.9.x-dev » 9.1.x-dev

Drupal 8.9.0-beta1 was released on March 20, 2020. 8.9.x is the final, long-term support (LTS) minor release of Drupal 8, which means new developments and disruptive changes should now be targeted against the 9.1.x-dev branch. For more information see the Drupal 8 and 9 minor version schedule and the Allowed changes during the Drupal 8 and 9 release cycles.

Version: 9.1.x-dev » 9.2.x-dev

Drupal 9.1.0-alpha1 will be released the week of October 19, 2020, which means new developments and disruptive changes should now be targeted for the 9.2.x-dev branch. For more information see the Drupal 9 minor version schedule and the Allowed changes during the Drupal 9 release cycle.

jeroent’s picture

Status: Needs review » Needs work
Issue tags: +Needs reroll
kapilv’s picture

Assigned: Unassigned » kapilv
kapilv’s picture

Assigned: kapilv » Unassigned
Status: Needs work » Needs review
Issue tags: -Needs reroll
StatusFileSize
new1.93 KB
new1.89 KB
jeroent’s picture

Status: Needs review » Needs work
+++ b/core/lib/Drupal/Core/Template/TwigExtension.php
@@ -110,6 +111,7 @@ public function getFilters() {
+      new \Twig_SimpleFilter('children', [$this, 'children']),

Twig_SimpleFilter is deprecated. We should replace this with TwigFunction.

anmolgoyal74’s picture

Status: Needs work » Needs review
StatusFileSize
new1.92 KB
new754 bytes

Update TwigFunction.

jeroent’s picture

Status: Needs review » Needs work

I’m sorry, i meant TwigFilter..

Also remove the leading backslash.

anmolgoyal74’s picture

Status: Needs work » Needs review
StatusFileSize
new1.92 KB
new746 bytes

Version: 9.2.x-dev » 9.3.x-dev

Drupal 9.2.0-alpha1 will be released the week of May 3, 2021, which means new developments and disruptive changes should now be targeted for the 9.3.x-dev branch. For more information see the Drupal core minor version schedule and the Allowed changes during the Drupal core release cycle.

Version: 9.3.x-dev » 9.4.x-dev

Drupal 9.3.0-rc1 was released on November 26, 2021, which means new developments and disruptive changes should now be targeted for the 9.4.x-dev branch. For more information see the Drupal core minor version schedule and the Allowed changes during the Drupal core release cycle.

vikashsoni’s picture

Applied patch #27 changes made in TwigExtension.php

jeroent’s picture

StatusFileSize
new4.21 KB

Added test coverage.

cburschka’s picture

I was about to point out the redundant is_array check but it looks like it disappeared from #31 which was added while I was typing :D

Version: 9.4.x-dev » 9.5.x-dev

Drupal 9.4.0-alpha1 was released on May 6, 2022, which means new developments and disruptive changes should now be targeted for the 9.5.x-dev branch. For more information see the Drupal core minor version schedule and the Allowed changes during the Drupal core release cycle.

Umit made their first commit to this issue’s fork.

Version: 9.5.x-dev » 10.1.x-dev

Drupal 9.5.0-beta2 and Drupal 10.0.0-beta2 were released on September 29, 2022, which means new developments and disruptive changes should now be targeted for the 10.1.x-dev branch. For more information see the Drupal core minor version schedule and the Allowed changes during the Drupal core release cycle.

needs-review-queue-bot’s picture

Status: Needs review » Needs work
StatusFileSize
new144 bytes

The Needs Review Queue Bot tested this issue. It either no longer applies to Drupal core, or fails the Drupal core commit checks. Therefore, this issue status is now "Needs work".

Apart from a re-roll or rebase, this issue may need more work to address feedback in the issue or MR comments. To progress an issue, incorporate this feedback as part of the process of updating the issue. This helps other contributors to know what is outstanding.

Consult the Drupal Contributor Guide to find step-by-step guides for working with issues.

ranjith_kumar_k_u’s picture

StatusFileSize
new4.17 KB

Re-rolled #31

ranjith_kumar_k_u’s picture

Status: Needs work » Needs review
smustgrave’s picture

Status: Needs review » Needs work
Issue tags: +Needs Review Queue Initiative, +Needs issue summary update, +Needs change record

Happy to see there are tests in there.

The issue summary should be updated with what is being added, The "why" is there. Would recommend using default issue template.

If we are adding a new twig function or way to render it will need a change record.

=====

Just FYI to help get the message out there.

Starting March 2023, simple rerolls, rebases, or merges will no longer receive issue credit. Only rerolls that address a merge conflict will be credited, and the merge conflict that was resolved must be documented in the text of an issue comment.

Example
error: patch failed: core/modules/system/tests/modules/twig_theme_test/twig_theme_test.module:77
error: core/modules/system/tests/modules/twig_theme_test/twig_theme_test.module: patch does not apply

To receive credit for contributing to this issue, assist with other outstanding tasks or unaddressed feedback.
See the issue credit guidelines for more information.

Version: 10.1.x-dev » 11.x-dev

Drupal core is moving towards using a “main” branch. As an interim step, a new 11.x branch has been opened, as Drupal.org infrastructure cannot currently fully support a branch named main. New developments and disruptive changes should now be targeted for the 11.x branch, which currently accepts only minor-version allowed changes. For more information, see the Drupal core minor version schedule and the Allowed changes during the Drupal core release cycle.

sime’s picture

Wow, this gets the award for the simplest patch I didn't know i needed. Very neat.

gcalex5’s picture

StatusFileSize
new4.59 KB

Re-roll #37 against 11.2.x

Version: 11.x-dev » main

Drupal core is now using the main branch as the primary development branch. New developments and disruptive changes should now be targeted to the main branch.

Read more in the announcement.