Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How To Display HTML Tags Saved In Database Using Symfony 2 and Twig

I've managed to build a page that will display data from the database dynamically. However, this code which is saved in the database:

<p>This is the content for the radio <a href="#">page</a>.</p>

Displays like this:

<p>This is the content for the radio <a href="#">page</a>.</p>

The HTML tags aren't rendered. I understand that Symfony (for security purposes) renders any HTML code like this for security reasons. I want Symfony (obviously) to render these HTML tags. How can I achieve this just for this purpose only, so that Symfony still sanitises any HTML tag that is saved to the database elsewhere on the site?

For your information as well, this is the code that I am using to pull the data from the database:

    public function mainpageAction($slug)
{

    $content = $this->getDoctrine()
        ->getRepository('SiteMainBundle:Content')
        ->find($slug);

    if (!$content) {
        throw $this->createNotFoundException('No product found for slug '.$slug);
    }

    return $this->render('SiteMainBundle:Default:page.html.twig', array('content' => $content, 'slug' => $slug));
}

Also, just so I can learn more about Symfony, is the rendering of the HTML tags just the sole job of PHP or could it be rendered properly using Twig?

Many thanks!

like image 578
mickburkejnr Avatar asked Aug 19 '11 10:08

mickburkejnr


1 Answers

If you want to do that, you need to use the raw filter in the twig template. Like described in the twig documentation, the raw filter marks the value as safe which means that in an environment with automatic escaping enabled this variable will not be escaped if raw is the last filter applied to it.

In your case, it's : {{ content | raw }}

like image 141
egeloen Avatar answered Oct 15 '22 06:10

egeloen