0

I am printing fields in a node template, but Twig is escaping my tags and ruining my day.

My .tpl looks like this:

  <blockquote>
    <p class="title">{{ content.field_myfield.0 }}</p>
  </blockquote>

I want to strip all tags from the original field and then "wrap" the field in a paragraph tag with the title class. I found out how to get the raw value without tags based on this question.

However, this is the HTML that is actually output:

<blockquote>
  <p class="title"></p><p>When you wish upon a star</p><p></p>
</blockquote>

What am I doing wrong?

1
  • content.field_myfield.0|render|striptags|trim . Can we try something like this. Commented May 11, 2020 at 13:11

1 Answer 1

2

You can use the following code below:

{{content.field_myfield.0|render|striptags|trim}}

render: The striptags filter strips SGML/XML tags and replaces adjacent whitespace by one space. You can also provide tags which should not be stripped:

{{ content.field_myfield.0|striptags('<br><p>')}}

trim: The trim filter strips whitespace (or other characters) from the beginning and end of a string:

{{ '  I like Twig.  '|trim }}

{# outputs 'I like Twig.' #}

{{ '  I like Twig.'|trim('.') }}

{# outputs '  I like Twig' #}

{{ '  I like Twig.  '|trim(side='left') }}

{# outputs 'I like Twig.  ' #}

{{ '  I like Twig.  '|trim(' ', 'right') }}

{# outputs '  I like Twig.' #}

The example above used from the twig website.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.