How to display string that contains HTML in twig template?

PhpHtmlSymfonyTwig

Php Problem Overview


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?

Php Solutions


Solution 1 - Php

Solution 2 - Php

You can also use:

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

so that only <b> tag will be allowed.

Solution 3 - Php

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

if you want to allow multiple tags

Solution 4 - Php

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionGildas RossView Question on Stackoverflow
Solution 1 - PhpAurimas LičkusView Answer on Stackoverflow
Solution 2 - PhpShimon SView Answer on Stackoverflow
Solution 3 - PhpmusicjermView Answer on Stackoverflow
Solution 4 - Phpbcag2View Answer on Stackoverflow