misterlewy1 misterlewy1 - 1 year ago 81
Twig Question

Twig doesn't render html tags, |raw doesn't work

I've got a simple blog application written in Symfony3, I'm using TinyMCE as a my text editor.
I'm storing data in database, where example record looks like this:

<p>Lorem ipsum</p>

I get articles from DB using this method:

* @Template

public function adminAction()
$repository = $this->getDoctrine()->getRepository('BlogBundle:Post');

$lastPosts = $repository->findBy(
array('id' => 'DESC'), 4

return array(
'last_posts' => $lastPosts,

And handle returned values in twig like this (It's just a part of code):

<div class="panel-body">

And the output looks like this:

<p>Lorem ipsum</p>

What should I do to get rid off html tags and just let them render. I've tried to clear cache, same result :(

Answer Source

I don't know why you have &lt;p&gt;Lorem ipsum&lt;/p&gt; as HTML content in your database, since it is NOT HTML, it is escaped HTML. Using raw unescapes the content, so your escaped HTML becomes... wait for it... HTML. And since twig escapes automatically HTML, that's why tags are displayed on your page.

What you could try as a quick fix is {{post.text|raw|raw}} to unescape the unescaped HTML. But honestly, what I would recommend for the sanity of your application is to unescape the HTML directly in your database. You SHOULD have <p>Lorem ipsum</p> in your database, then using {{post.text|raw}} should work perfectly.