Last active
April 1, 2019 14:07
-
-
Save mattschaff/e11132f345a6608de6867289d594f6a5 to your computer and use it in GitHub Desktop.
Drupal 8: Outputting Data with Twig
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{# | |
/** | |
* The below assumes Twig Tweak and Twig Extensions are installed | |
* | |
* Also this is a great reference: https://blog.usejournal.com/getting-drupal-8-field-values-in-twig-22b80cb609bd | |
*/ | |
#} | |
{# Drupal Block #} | |
{{ drupal_block('block_machine_name') }} | |
{{ drupal_block('views_block:view_machine_name-display_name') }} | |
{# Drupal entity #} | |
{{ drupal_entity('block', 'block_machine_name') }} | |
{# Add class to attributes array #} | |
{{ attributes.addClass('new-class') }} | |
{# Title in node.html.twig #} | |
{{ label }} | |
{# | |
/** | |
* Fields | |
*/ | |
#} | |
{# Pre-formatted field #} | |
{{ content.field_test }} | |
{# Unformatted value of field #} | |
{{ content.field_test.value }} | |
{# List field value (display set to 'Key') #} | |
{{ content.field_list_field['#items'].getString() }} | |
{# Date with custom date format #} | |
{{ content.field_date.value | date('Y-m-d') }} | |
{# Path of taxonomy term #} | |
{{ path('entity.taxonomy_term.canonical', {'taxonomy_term': content.field_tags.0.entity.tid.value} }} | |
{# Number of elements in multi-field #} | |
{{ content.field_tags|length }} | |
{# Multi-value field#} | |
{% if content.field_tags[0] %} | |
<ul> | |
{% for key, item in content.field_tags %} | |
<li>{{ item }}</li> | |
{% endfor %} | |
</ul> | |
{% endif %} | |
{# Image src #} | |
{{ file_url(content.field_image.entity.uri.value) }} | |
{# Image style #} | |
{{ content.field_image['#items'].entity.uri.value | image_style('custom_image_style') }} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment