Twig reference


{% (this is a block) %}
${ (this is an expression) }
${ this_is_also_a_variable }
${ variable | this_is_a_filter("and", "these are", arguments) }
this == is + an ~ "expression"
{# this is a comment, and is removed when the template is built #}

Block Twig

down vote

In a block twig you can access a field value like this:

{{ content['#block_content'].field_myfield.value }}

This is the database value of the field.

Most times you want to render a field:

{{ content.field_myfield }}

This will display the field as it is configured in the view mode.

Twig |length filter

New in version 2.3: Support for the __toString() magic method has been added in Twig 2.3.

The length filter returns the number of items of a sequence or mapping, or the length of a string.

For objects that implement the Countable interface, length will use the return value of the count() method.

For objects that implement the __toString() magic method (and not Countable), it will return the length of the string provided by that method.

{% if users|length > 10 %}
{% endif %}

Node type twig

You should be able to get the human-readable name of the content type (or the "label") by doing {{ node.type.entity.label }} in your node Twig template.

Twig taxonomy term entity reference ID

down vote
I figured it out, I was able to print the term ID of the category field using:

{{ node.field_category.entity.tid.value }} as I realised I was looking in the wrong direction. Drupal 8 use entity reference only so I needed to call the TID from the referenced entity which of course is a taxonomy term in my category field.