Contents

09/27/2026

Twig strict_variables: errors or silent null

strict_variables decides what Twig does with a variable, attribute or method that doesn't exist. Set to false, Twig quietly treats it as null. Set to true, it throws an error. Plain Twig defaults to false. Symfony defaults it to %kernel.debug%, so it's on in dev and off in prod.

Setting it

In Symfony, in config/packages/twig.yaml:

twig:
    strict_variables: true

In plain Twig, when you create the environment:

$twig = new \Twig\Environment($loader, [
    'strict_variables' => true,
]);

Both are documented: Twig's environment options and Symfony's Twig configuration reference.

Why a template works locally and misbehaves in production

With Symfony's default, a typo such as {{ user.nmae }} throws in dev, where you'd notice it, and prints nothing in prod, where you won't. That split is deliberate, and it's usually the right one. Turning it off in dev hides typos. Turning it on in prod makes a missing optional field an error page for visitors.

Handling a value that may be missing

With strict variables on, say what should happen when a value is absent:

{{ user.nickname ?? user.name }}
{{ subtitle|default('') }}
{% if promo is defined %}{{ promo.code }}{% endif %}

?? returns the left side if it's defined and not null. default returns its argument if the value is undefined or empty. Twig's defined test is described as "very useful if you use the strict_variables option".

One difference matters: default treats false and empty strings as missing too. Twig's default filter page suggests ?? when false is a real value.

How to verify

Put a deliberate typo in a template and load the page in dev. You should get an error page naming the missing attribute. In prod the same page renders with a gap, which is the behavior worth knowing about before it happens. The Twig cheat sheet covers the rest of the syntax.

Questions this raises

What is the default value of strict_variables?

false in plain Twig. In Symfony it defaults to %kernel.debug%, so it's true in dev and false in prod.

Does is defined work when strict_variables is on?

Yes. Twig's documentation describes the defined test as very useful with strict_variables, and ?? and the default filter also handle undefined values without throwing.

Does strict_variables cover methods and array keys, or only variables?

It covers variables and attributes. In Twig an attribute is whatever a dot or square brackets reach: an object property or method, or an array key.

Should I turn strict_variables on in production?

Usually not. In production a missing optional value would become an error page for visitors. Keep it on in development and tests, where an error is what you want.