mickburkejnr
mickburkejnr

Reputation: 3690

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!

Upvotes: 6

Views: 12352

Answers (1)

egeloen
egeloen

Reputation: 5864

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 }}

Upvotes: 23

Related Questions