Drupal - How do I get the raw field value in a twig template?

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

  • Example: {{ node.body.value }}
  • result: <p>Batman &amp; Robin</p>

{{ content.field_name.0 }} to get the raw value minus tags and encoding.

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

raw

This filter should be avoided whenever possible, particularly if you're outputting data that could be user-entered. See this page for more information on auto-escape in Drupal 8.

source: Filters - Modifying Variables In Twig Templates

The raw filter marks the value as being "safe", which means that in an environment with automatic escaping enabled this variable will not be escaped if raw is the last filter applied to it

source: Twig's official docs


For example, you can use:

{{ node.body.value|striptags }}
{{ paragraph.field_text.value|striptags }}

The problem with using twig's |striptags is double encoding of html entities, not markup, so & becomes &amp; and then &amp;amp; – Berdir


You can use Twig Field Value module in this case. After install this module You will get access to partial data from field render arrays. For ex.

{{ content.field_name|field_value }}
content.field_image|field_target_entity.uri.value

etc. More info on projects page


{{ content.body | raw }} 

get the raw field value in a twig template

Tags:

Theming

8