Skip to the stories
AI & ML

Twig 4.0 Beta Tightens Sandboxing and Speeds Up Template Loops

  • Fabien Potencier
  • 536 reads

Twig 4.0 beta removes deprecated 3.x behavior, adds stricter sandbox rules and cuts loop overhead. Teams can start checking migration issues now.

Twig 4.0 Beta Tightens Sandboxing and Speeds Up Template Loops

Twig 4.0 beta turns the cleanup work in Twig 3.x into concrete compatibility changes, while also reducing the cost of common template loops. For teams that maintain Twig extensions, bundles or applications, the practical signal is clear: the latest Twig 3.x deprecation notices now serve as a migration checklist. Code that runs without those notices should be ready for Twig 4.0, according to the project.

Fabien Potencier

The beta follows the first alpha by six months. It includes the changes made across Twig 3.x through version 3.31.1, alongside the removals and updates prepared on the 4.x branch. That makes it useful for early compatibility checks, even as a beta release leaves room for further changes before the final version.

Sandboxing gets a clearer boundary

The security model for rendering untrusted templates is one of the release’s largest changes. A dedicated Sandbox now owns its own Twig environment, giving sandboxed rendering a distinct execution context. The render_sandboxed() function takes over the role previously handled by the sandboxed argument to include().

The sandbox also checks more than direct access to properties and methods. Tests, parent(), block() and attribute() calls are evaluated against the configured policy. At the same time, harmless built-in tags, filters and functions are always allowed. The attributes of the loop variable are also permitted, so a policy no longer needs to list the loop object’s methods.

That combination changes both the structure and day-to-day configuration of sandboxed templates. The separate environment makes the boundary easier to reason about, while the built-in allowances remove repetitive setup for common template operations. Teams with custom sandbox policies should still check how the expanded checks interact with their permitted template features.

Nicolas Grekas

Macros follow function-like rules

Twig 4.0 also makes macros stricter about how they receive arguments. They now handle arguments like functions, and a macro call missing its parentheses produces a SyntaxError. The change brings a more consistent calling convention, but templates that relied on loose macro syntax will need to be corrected.

Loop behavior gets a more direct performance improvement. In earlier work on Twig 4.0, access to the loop object added overhead because each loop body ran inside a closure and iterated through a LoopIterator. The beta avoids that path when it isn't needed: loops that don't use loop iterate natively, and loops that only read its attributes no longer require a closure.

The reported impact is specific to Symfony’s form_div_layout.html.twig, where rendering executes more than 20% fewer instructions. That figure describes instruction count for this template; it doesn't establish the same improvement for every application or measure wall-clock response time. The underlying change is still relevant to teams with loop-heavy templates, but they’ll need to assess its effect with their own workloads.

Other loop details return to Twig 3.x behavior: a sequence is rewound only once, and macros imported inside a loop remain available after it. There’s also a correction to the loop else clause. When a condition filters out every item, the else body now renders, giving templates a way to display an empty result for cases such as a list with no active users.

Extension authors should check signatures and node behavior

Much of the remaining work removes paths deprecated during Twig 3.x. Cloning a Twig\Environment now throws an exception, so code that needs another environment must create one. TemplateWrapper::unwrap() now requires the environment as an argument, and Twig\Markup is final.

Several extension points also become more explicit. TwigCallableInterface and TokenParserInterface gain an isAlwaysAllowedInSandbox() method. Deprecation getters on TwigCallableInterface are replaced by AbstractTwigCallable::triggerDeprecation(). Changes to IncludeNode::addGetTemplate(), FilesystemLoader::addPath() and FilesystemLoader::prependPath() add arguments that overriding methods must declare.

Compiled nodes must use yield. Twig no longer checks compiled nodes for echo or print; the #[YieldReady] and #[FirstClassTwigCallableReady] attributes are therefore inert. Their classes remain available so code that supports both Twig 3 and 4 can still pass static analysis.

There are changes for test suites and custom nodes, too. IntegrationTestCase and NodeTestCase declare native return types, and integration test data providers are named provideTests() and provideLegacyTests(). MacroNode can no longer be extended; the TemplateVariable and AssignTemplateVariable nodes give way to MacroVariable and AssignMacroVariable. The autoescape tag also rejects strategies other than a string or false at compile time.

For maintainers, the most efficient first pass is to run the latest Twig 3.x version and resolve every deprecation it reports, then check custom extensions for changed method signatures and node assumptions. The Twig 3.x deprecation guide describes migration steps, and the Twig 4.0 beta changelog lists the full set of changes. The next useful signal will be whether beta testing uncovers compatibility issues beyond the legacy paths already removed.

Source: Fabien Potencier · symfony.com

From the same set