Doctrine entities in Twig templates

In a Symfony2 project, Doctrine entities can be used inside Twig templates with the help of Twig extensions.

The example works with the standard Symfony2 installation and the AcmeDemoBundle, and it is supposed to add a set of links on one of the demo pages. Each link represents a color, while the HEX code for that color is displayed when the link is clicked. The colors are retrieved from the database.

The example is using Twig functions, but an alternative which is using global variables is also presented.

The Doctrine entity:

This entity has a basic structure which should store the name and HEX code for a color.

The Twig extension:

The following list contains the most important remarks related to the Twig extension:

  • The string returned by the “getName” ┬ámethod – “color_extension” will be used to register the extension;
  • The “getColors” method is the one which returns the entities, using the EntityManager;
  • In order to have access to the EntityManager, the Twig extension needs to be registered by specifying that the EntityManager service (identified as “doctrine.orm.entity_manager”) will be passed as argument;
  • The key “get_colors” from the array returned by the “getFunctions” method is the actual Twig function name which needs to be called in the Twig template to return the entities.

Twig extension registration:

In order to register the Twig extension the following piece of code needs to be added to src/Acme/DemoBundle/Resources/config/services.xml:

As previously mentioned, the “color_extension” string is used in the service id and the EntityManager service is sent as parameter for the Twig extension.

Everything should be set by now, the only thing that needs to be done is to call the “get_colors” function inside a Twig template. Here’s an example:

The global variables alternative.

Update the Twig extension (src/Acme/DemoBundle/Twig/Extension/ColorExtension.php) with the following code:

This means that the “colors” key will become a global variable and can be used in a Twig template.