Code Snippets

Twig & Doctrine

Templates and mappings, which is where the time actually goes - Twig syntax, escaping, and the Doctrine queries behind what a template renders.

Four notes on where Twig templates and Doctrine queries meet, and where that goes wrong.

The N+1 you wrote in a Twig loop: a lazy association loads the moment a template touches it, one query per row. Autoescaping and the raw filter explains why HTML escaping is only correct in HTML. strict_variables decides whether a missing variable throws or becomes null. Reading a cookie value in a Twig view is the short one.

Search these 6 posts

Everything in Twig & Doctrine

  • Title card: Twig strict_variables: errors or silent null

    09/27/2026

    Twig strict_variables: errors or silent null

    strict_variables makes Twig throw on a missing variable, attribute or method instead of using null. Symfony turns it on in dev and off in prod.

  • Diagram: autoescape on, punctured by |raw, with three contexts named where that filter is the wrong answer -- attribute, URL, inline JS and CSS.

    09/02/2026

    Twig autoescaping and the raw filter

    Autoescaping makes Twig safe by default and makes |raw the fastest way to undo that. The catch is that HTML escaping is only correct in HTML - inside a script tag or an unquoted attribute, the default is the wrong answer.

  • Diagram: a loop firing fifty queries at a database, compared against the same loop firing one query after addSelect().

    09/02/2026

    The N+1 you wrote in a Twig loop, and its fix

    The query looks fine and the template looks fine. Together they issue one query per row, because a lazy association is loaded the moment a template touches it - and templates touch things the controller never did.

  • Rendering Twig from Symfony Repositories Without DI

    07/04/2019

    Rendering a Twig template outside a controller

    You do not need a controller to render Twig, and you should not pass the container around to get at it. Inject the Environment, and use createTemplate when the template itself comes from the database.

  • Diagram: a browser's cookie flowing into a Symfony Request object and out into a Twig template reading app.request.cookies.get('name').

    04/02/2015

    How to show or access cookie values in Symfony Twig views

    Strange how obscure it is to find a clear example of how to just access or show the value of a cookie in Twig, so here it is!

  • Symfony Dynamic Form Collections and data-prototype in Twig

    06/24/2014

    Symfony collection prototype: formatting it in Twig

    Let’s say you are creating a form in Symfony that has some dynamic fields that you need to allow the user to add and remove a subset of options and fields from within the form.