Drupal - How to correctly access entity elements in a twig template

As the exception explains, you tried to print an object that is not renderable and cannot be converted to a string. In this case it was Drupal\Core\Field\FieldItemList which is the object returned by drupal entities when you ask for a field ({{ entity.id }} / {{ entity.label }}).

To get the actual value you need to call to methods of your entity (the actual value of the fields is protected from outside access).

The long way:

{{ entity.get('id').get(0).get('value').getValue() }}

The above is the actual path you need to take to get from the entity object to the value of the id field.

However drupal supplies shortcuts through what is known as magic properties. The short way

{{ entity.id.value }}

Tags:

Entities

8