How to Display String That Contains HTML in Twig Template

How to display string that contains HTML in twig template?

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

{{ word | raw }}

Print a variable that contains html and twig on a twig template

Twig can't render strings containing twig. There is not something like an eval function in Twig1..

What you can do is moving the path logic to the PHP stuff. The router service can generate urls, just like the path twig function does. If you are in a controller which extends the base Controller, you can simply use generateUrl:

$menuString .= '<li><a href="'.$this->generateUrl($actual['direction'].'">'. $actual['nombre'] .'</a></li>';

return $this->render('::menu.html.twig', array(
'menu' => $menuString,
));

Also, when using menu's in Symfony, I recommend to take a look at the KnpMenuBundle.


EDIT: 1. As pointed by @PepaMartinec there is a function which can do this and it is called template_from_string

TWIG variables with HTML tags

You can use the raw filter:
http://twig.sensiolabs.org/doc/filters/raw.html

<li><b>Description</b><br>
{{ description|raw }}
</li>

Render twig HTML string with twig-variable

You may use the template_from_string extension.

The template_from_string function loads a template from a string.

In your case, it should be something like this:

{{ include(template_from_string(html.editWorklogButton)) }}

twig template - how to render html inside twig template

Maybe auto-escaping is turned on.
You can have a look at the autoescape parameters for twig.

You can try wrapping your code between {% autoescape false %} and {% endautoescape %}.

Displaying malformed html with twig

sw_sanitize does this already.

{{ '<b> hello' | sw_sanitize }}

Produces:

<b> hello</b

Internally \HTMLPurifier::purify is used, which

Filters an HTML snippet/document to be XSS-free and standards-compliant.



Related Topics



Leave a reply



Submit