Drupal Twig template

Drupal Twig template: how to check the value of a field

Vedi L'articolo in Italiano

We work with Drupal 8 or 9 to create new content types or nice pages. Therefore we always use Twig templates.

Twig is the standard in Drupal version 8 while on Drupal 7 or earlier the templates were written in PHP.

If we need to render a field based on how it was configured in the content type we use the simple function in a Drupal Twig template:

{{ content.fieldname }}

and the field is rendered perfectly by Drupal.

We don’t always have to render the field as it is but we may just want to fetch its value.

So we can test or display it in HTML with different tags.

Therefore in the following paragraphs the main types of Drupal fields are analyzed.

We starting first from simple fields until “Entity reference” type.

In short we get data usefull to develop the site.

Drupal fields

Introduction

As a general hypothesis for each field that we will analyze we consider that the variable “node” returns the current node and that “fieldname” is the name (the machine name) of the field to be analyzed.

We always use the first element of field even, for example, if it is defined as a repeating field. We consider only the first element of the array of the field.

To clarify, if “fieldname” is a multiple of 3 elements then:

{{ node.fieldname[0] }} {# is the first element #}
{{ node.fieldname[1] }} {# is the second element #}
{{ node.fieldname[2] }} {# is the third element #}

On the other hand, if we consider the whole array we would have a FieldItemList type or its derivative. For instance, EntityReferenceFieldItemList or FileFieldItemList

{{ node.fieldname }} {# FieldItemList! #}

General fields group

For this type of fields the Namespace is unique and it is Drupal\Core\Field\Plugin\Field\FieldType

Boolean

Class: BooleanItem

{# value: returns the value "1" or "0" #}
{{ node.fieldname[0].value }}
{# getPossibleOptions(): returns an array of 2 elements whose keys are:
 "0" and "1" and the values are "On" and "Off" or those defined during the creation of the field  
 array { 
   0 => "On", 
   1 => "Off" 
 } 
#} 
{{ node.fieldname[0].getPossibleOptions() }}
{# getPossibleValues(): returns an array with possible values 
  array { 
    0 => 0, 
    1 => 1 
  } 
 #} 
 {{ node.fieldname[0].getPossibleValue() }}

Date

Class: DateTimeItem

{{ node.fieldname[0].value }}

Timestamp

Class: TimestampItem

{{ node.fieldname[0].value }}

Email

Class: EmailItem

{{ node.fieldname[0].value }}

Link

Class: LinkItem

{# node.uri: returns the uri of the url #}
{{ node.fieldname[0].value.uri }}
{# value.title: returns the title of the link #}
{{ node.fieldname[0].value.title }}
{# value: returns an array with url and title keys #}
{{ node.fieldname[0].value }}

Number fields group

Namespace: Drupal\options\Plugin\Field\FieldType

{{ node.fieldname[0].value }}

List (float) e List (integer)

Class: ListFloatItem e ListIntegerItem

{# value: returns the float or integer value #}
{{ node.fieldname[0].value }}
{# 
 # getPossibleValues(): Returns an array of possible values
 # array { 0 => "0.1", 1 => "0.55",2 => "18" } 
 #}
{{ node.fieldname[0].getPossibleValues() }}
{#
 # getPossibleOptions(): Returns an array of possible values with the labels for display
 #  array { 0.1 =>  "a tenth", 0.55 => "zero and 55", 18 =>   "eighteen" }
#}
{{ node.fieldname[0].getPossibleOptions() }}

Number (decimal, float, int)

Class: DecimalItem, FloatItem, IntegerItem

{# value: returns the decimal, float, or int value based on the type of field #}
{{ node.fieldname[0].value }}

Text fields group

Namespace: Drupal\options\Plugin\Field\FieldType

List (text)

Class: ListStringItem

{# value: returns the selected key #}
{{ node.fieldname[0].value }}
{# 
 # getPossibleValues(): Returns an array of possible values
 # array { 0 => "0.1", 1 => "0.55",2 => "18" } 
 #}
{{ node.fieldname[0].getPossibleValues() }}
{#
 # getPossibleOptions(): Returns an array of possible values with the labels for display
 #  array { 0.1 =>  "a tenth", 0.55 => "zero and 55", 18 =>   "eighteen" }
#}
{{ node.fieldname[0].getPossibleOptions() }}

Text (formatted, long, summary, plain)

Class: TextItem, TextLongItem, TextWithSummaryItem, StringItem, StringLongItem

{# value: returns text with html tags, if available #}
{{ node.fieldname[0].value }}
{# summary: returns the summary of the field if that field allows it #}
{{ node.fieldname[0].summary }}

Reference fields group

Namespace: Drupal\Core\Field\Plugin\Field\FieldType
Class: EntityReferenceItem or super class (like as File and Image)

Each field of the “Reference” group will then be an Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenceItem object or a class that extends it:

{# is an EntityReferenceItem object #}
{{ node.fieldname[0].entity }}

To get the entity, use:

{{ node.fieldname[0].entity }}

If we want the identity of the entity:

{{ node.fieldname[0].entity.id }}

Content

Namespace entity: Drupal\node\Entity
Class entity: Node

The object associated with the entity is of type “Node“.

We get the data:

{# nid.value: returns the node id #}
{{ node.fieldname[0].entity.nid.value }}
{# title.value: return the node title #}
{{ node.fieldname[0].entity.title.value }}
{# body.value: return the body #}
{{ node.field_test_ref_content[0].entity.body.value }}
{# | view: this renders the field #}
{{ node.field_test_ref_content[0].entity.body | view }}
{# created.value: returns the creation date #}
{{ node.field_test_ref_content[0].entity.created.value }}
{# | view: it renders the whole node #}
{{ node.field_test_ref_content[0].entity | view }}

Custom Block

Namespace entity: Drupal\block_content\Entity
Class entity: BlockContent

We find the main data of the block with:

{# id.value: return the block id #}
{{ node.fieldname[0].entity.id.value }}
{# info.value: return the description #}
{{ node.fieldname[0].entity.info.value }}
{# body.value: return the HTML of the body #}
{{ node.fieldname[0].entity.body.value }}
{# body.summary: returns the summary of the block #}
{{ node.fieldname[0].entity.body.summary }}
{# | view: this renders then block #}
{{ node.fieldname[0].entity | view }}

Taxonomy term

Namespace entity: Drupal\taxonomy\Entity
Class entity: Term

The data of the Taxonomy term field can be found with:

{# id.value: return the id of the term #}
{{ node.fieldname[0].entity.id.value }}
{# name.value: return the name of the term #}
{{ node.fieldname[0].entity.name.value }}
{# description.value: return the description #}
{{ node.fieldname[0].entity.description.value }}
{# | view: this renders the taxonomy term #}
{{ node.fieldname[0].entity | view }}

Media

Namespace entity: Drupal\media\Entity
Class entity: Media

Media is a complex field which has other fields. The main one, which distinguishes it among the various “Media types” (see /admin/structure/media for existing types and how to create others).

The main data of the Media field can be found with:

{# mid.value: return the media id #}
{{ node.fieldname[0].entity.mid.value }}
{# bundle(): return the name of the bundle #}
{{ node.fieldname[0].entity.bundle() }}
{# name.value: return the field's name of the Media #}
{{ node.fieldname[0].entity.name.value }}
{# | view: this renders the Media #}
{{ node.fieldname[2].entity | view }}

If the Media type is “Image” then the field will be “field_media_image“.
Audio” will have the “field_media_audio_file” and “Document” will have “field_media_document“.
For other Media types see the relevant page on Drupal.

In the case of “Image” we find the “field_media_image” field with

{{ node.fieldname[0].entity.field_media_image }}

This field is an “ImageItem” type object. Therefore, we can find all usefull fields such as: width, height, alt, the file name, the uri, the url, the mime type and the size in bytes. To better undestand see below in the File and Image paragraph.

File

Class: FileItem (extends EntityReferenceItem)

The FileItem class adds some more features than EntityReferenceItem. This can be summarized in this Drupal Twig template:

{# description: return the description #}
{{ node.fieldname[0].description }}
{# getUploadLocation(): return the dir uri to upload (public://2021-02) #}
{{ node.field_test_ref_file[0].getUploadLocation() }}
{# file_url: return the relative path to upload (/sites/default/files/2021-02) #}
{{ file_url(node.field_test_ref_file[0].getUploadLocation()) }}

Namespace entity: Drupal\file\Entity
Class entity: File

{# getFilename(): return the name of the file #}
{{ node.fieldname[0].entity.getFilename() }}
{# getFileUri(): return the internal uri (public://2021-01/test.txt or private://2021-01/test.txt) #}
{{ node.fieldname[0].entity.getFileUri() }}
{# getMimeType(): return the mime type #}
{{ node.fieldname[0].entity.getMimeType() }}
{# getSize(): return the size in byte #}
{{ node.fieldname[0].entity.getSize() }}
{# file_url(): return the relative url to the base installation of Drupal #}
{{ file_url(node.fieldname[0].entity.getFileUri()) }}

Image

Class: ImageItem (extends FileItem, extends EntityReferenceItem)

The ImageItem class adds some more features than FileItem and EntityReferenceItem. This can be summarized in this Drupal twig template:

{# alt: return the alternative text #}
{{ node.fieldname[0].alt }}
{# title: return the image title #}
{{ node.fieldname[0].title }}
{# width: return the image width #}
{{ node.fieldname[0].width }}
{# height: return the image height #}
{{ node.fieldname[0].height }}

Namespace entity: Drupal\file\Entity
Class entity: File

The Class and Namespace are identical to the File entiy. As result the same Twig calls apply: getFilename(), getFileUri(), getMimeType() and getSize().

References

Namespaces

Classes

Leave a Reply

Your email address will not be published. Required fields are marked *

57 + = 66