Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save davidjguru/99392427b73493f8adfc07ea5f4f563b to your computer and use it in GitHub Desktop.
Save davidjguru/99392427b73493f8adfc07ea5f4f563b to your computer and use it in GitHub Desktop.
Drupal 8 || 9 || 10 - TWIG templates: Getting files in taxonomy terms media fields from a Drupal node

Drupal 8 || 9 || 10 - TWIG templates: Getting files in taxonomy terms media fields from a Drupal node

Sometimes, we have to build a file download button from a twig template. This can be done in many ways, but one of the most common use cases is to implement it directly from a twig template specific to that content type.

This gist covers a small and very specific use case where the file is part of a media type field present in a taxonomy term that is used in nodes of a content type: to extract the file path and form the download button path, we must traverse several levels..

Author

From a file of the type page--node--content-type-name.html.twig, you can use something like:

{% if node and node.field_taxonomy_term is not empty %}
    {% set term = node.field_taxonomy_term.entity %}
    {% if term and term.field_media_field is not empty %}
        {% set media = term.field_media_field.entity %}
          {% if media and media.field_media_document is not empty %}
            {% set file = media.field_media_document.entity %}
                {% set file_url = file.uri.value %}
                  <div class="download-button">
                    <a class="button download" href="{{ file_url|file_url }}?download=true" title={{"Download file"|t}}>{{"Download file"|t}}</a>
                  </div>
          {% endif %}
    {% endif %}
{% endif %}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment