0

I have a content type called publication which results the node's twig template: node--publication.html.twig. This content type contains a multiple file fields where the description is allowed.

I would like to share it with you, because it took a lot of time for me to find out how can I iterate through and render the items of a FileFieldItemList which would be a very easy thing without the drupal theming system.

Some of you might find useful it.

0

I am able to access the uri, and I can generate url from it by a Twig filter.

{{ content.field_document.0['#file'].uri.value|urlFromUri }}
{{ content.field_document.1['#file'].uri.value|urlFromUri }}
{{ content.field_document.2['#file'].uri.value|urlFromUri }}

and the description:

{{ content.field_document.0['#description'] }}
{{ content.field_document.1['#description'] }}
{{ content.field_document.2['#description'] }}

the Twig filter:

<?php

namespace Drupal\something_general\TwigExtension;

use Drupal\Core\Url;


class Custom extends \Twig_Extension
{

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


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


  /**
   * @param $uri
   */
  public static function UrlFromUri($uri)
  {
    $realpath = drupal_realpath($uri);
    $path = str_replace($_SERVER['DOCUMENT_ROOT'], '', $realpath);

    return $path;
  }

}

I am also able, to get the number of the items of the FileFieldItemList:

{% for index in 1..node.field_document.getValue|length %}
{% endfor %}

And finally the iteration in the node--publication.html.twig file:

{% for index in 1..node.field_document.getValue|length %}
  {% set document = content.field_document[ (index-1) ] %}

  {{ dump(document['#file'].uri.value|urlFromUri) }}
  {{ dump(document['#description']) }}

{% endfor %}
| improve this answer | |

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.