208

How can I display a string that contains HTML tags in twig template?

My PHP variable contains this html and text:

$word = '<b> a word </b>';

When I do this in my twig template:

{{ word }}

I get this:

&lt;b&gt; a word &lt;b&gt;

I want this instead:

<b> a word </b>

Is it possible to get this easily?

Ramratan Gupta
  • 1,056
  • 3
  • 17
  • 39
Gildas Ross
  • 3,812
  • 5
  • 21
  • 31
  • I won't add this as an answer, but an alternative approach for people reaching this question is to store values in [Markdown](https://packagist.org/packages/michelf/php-markdown), like [StackOverflow does](https://stackoverflow.com/editing-help). Then you could create a Twig filter with [automatic escaping](https://twig.symfony.com/doc/2.x/advanced.html#automatic-escaping), since you can trust the HTML to be safe. No `raw` needed, and your stored values are human readable! – rybo111 Jul 15 '19 at 21:13

5 Answers5

450

Use raw keyword, https://twig.symfony.com/doc/3.x/api.html#escaper-extension

{{ word | raw }}
WoodrowShigeru
  • 1,418
  • 1
  • 18
  • 25
Aurimas Ličkus
  • 9,886
  • 4
  • 24
  • 26
  • 1
    When doing a replace it is not working for me. {{ word | replace( {(word_to_replace) : '' ~ (word_to_replace) ~ '' }) | raw }} Any idea? – Honesta Oct 13 '16 at 11:42
  • 3
    UPDATE: I solved it by adding it to another variable using 'set', then {{ word | raw }} works fine. – Honesta Oct 13 '16 at 12:02
88

You can also use:

{{ word|striptags('<b>')|raw }}

so that only <b> tag will be allowed.

Shimon S
  • 4,048
  • 2
  • 29
  • 34
40
{{ word|striptags('<b>,<a>,<pre>')|raw }}

if you want to allow multiple tags

musicjerm
  • 400
  • 3
  • 5
1

if you don't need variable, you can define text in
translations/messages.en.yaml :
CiteExampleHtmlCode: "<b> my static text </b>"

then use it with twig:
templates/about/index.html.twig
… {{ 'CiteExampleHtmlCode' }}
or if you need multilangages like me:
… {{ 'CiteExampleHtmlCode' | trans }}

Let's have a look of https://symfony.com/doc/current/translation.html for more information about translations use.

bcag2
  • 1,988
  • 1
  • 17
  • 31
0

Worked for me only with "render" before striptags:

node--mycontenttype.html.twig:

{{ content.field_my_field|render|striptags }}
Thomas
  • 76
  • 8