Saturday, 16 June 2012

Include custom PHP-generated html code using Twig and Symfony 2


How do I embed custom HTML code (or scripts, etc.) into a page generated from a Twig template?

This is useful because:

For instance, if a page controller in Symfony 2 is used to generate a fancy widget, such as a calendar, you may want to have a way for the twig template to render this custom server-side generated code.


Pass the customized html string into a parameter in the twig template (customcodeparam, in the example below), and use the raw filter when rendering, e.g.

{{ customcodeparam | raw }}

Detailed example:

This example is not 100% complete, but it should include enough code to convey the idea of how to embed custom code into a twig template. This example assumes that you're already familiar with PHP and Symfony 2, and are learning Twig.

Imagine that you have a twig template named 'something.twig':

{# MyBundle:Page:something.twig #}
{% extends 'MyBundle:Page:index.html.twig' %}

{% block body %}
<h1>My awesome custom server-side-generated widget</h1>
{{ customcodeparam | raw }}
{% endblock %}

And also imagine that there was a page controller that rendered the template:

public function renderSomethingAction(){

  // replace the code below with your own
  $widgetcode = "<a href=''>Go Google!</a>";

  try {
         return $this->render('MyBundle:Page:something.html.twig',
                        'customcodeparam' => $widgetcode
  } catch (\Doctrine\ORM\NoResultException $e) {
         return null;

The resulting rendered html in the body block would look similar to the following:

<h1>My awesome custom server-side-generated widget</h1>
<a href=''>Go Google!</a>

(Note that the above code snippet does not include the html generated by MyBundle:Page:index.html.twig)


This probably goes without saying, but just a reminder that when including un-sanitized code that is generated by your server-side script on your web app, you should ensure that this code is safe. This is especially important to consider if the inserted code includes user-generated content (in case a user decides to sneak in a script, etc.). In other words, when using the trick in this post, the sanitization of the page is now up to you and not up to Twig. Pretty basic, I know, but I thought I should mention it anyway.

No comments:

Post a Comment