How to display string that contains HTML in twig template?
Asked Answered
O

5

212

How can I display a string that contains HTML tags in a 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?

Overtake answered 2/12, 2011 at 10:44 Comment(1)
I won't add this as an answer, but an alternative approach for people reaching this question is to store values in Markdown, like StackOverflow does. Then you could create a Twig filter with automatic escaping, since you can trust the HTML to be safe. No raw needed, and your stored values are human readable!Wheelchair
B
458

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

{{ word | raw }}
Broomrape answered 2/12, 2011 at 10:55 Comment(2)
When doing a replace it is not working for me. {{ word | replace( {(word_to_replace) : '<b>' ~ (word_to_replace) ~ '</b>' }) | raw }} Any idea?Repose
UPDATE: I solved it by adding it to another variable using 'set', then {{ word | raw }} works fine.Repose
R
88

You can also use:

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

so that only <b> tag will be allowed.

Rayford answered 8/5, 2012 at 19:12 Comment(2)
I'd say this version is preferable if you want to allow only a few tags.Parity
How do you allow multiple tags?Assist
B
40
{{ word|striptags('<b>,<a>,<pre>')|raw }}

if you want to allow multiple tags

Blockhead answered 9/6, 2016 at 17:2 Comment(0)
S
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.

Sleet answered 1/7, 2020 at 12:18 Comment(0)
T
0

Worked for me only with "render" before striptags:

node--mycontenttype.html.twig:

{{ content.field_my_field|render|striptags }}
Thumbscrew answered 6/3, 2023 at 14:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.