Twig values

URL in link field
{{ node.field_my_link.0.url }}

{{ entity.field_name.value }} to get the true raw value, includes tags and encoding.

Example: {{ node.body.value }}
result: Batman & Robin
{{ content.field_name.0 }} to get the raw value minus tags and encoding.

Example: {{ content.body.0 }}
result: Batman & Robin

Term ID
{{ node.field_category.entity.tid.value }}

Drupal 8 – Formatting a Date Field in Twig

Here are the four easiest ways I’ve found to show dates via Twig inside of a node template.

They all result in the same output.

Use the field’s formatter settings; include wrappers

{{ content.field_blog_date }}
{{ content.field_blog_date }}
This is the only example that includes wrappers. The rest output just the date.

Use the field’s formatter settings

{{ content.field_blog_date.0 }}
{{ content.field_blog_date.0 }}
This will use the format defined in Content type » Manage Displays » Your View Mode.

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.