177
votes

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?

4
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!rybo111

4 Answers

80
votes

You can also use:

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

so that only <b> tag will be allowed.

35
votes
{{ word|striptags('<b>,<a>,<pre>')|raw }}

if you want to allow multiple tags

1
votes

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.