Hi, I'm Liam

I talk about code and stuff

Twig Push/Stack Extension

Published on

When working with Twig, you might find yourself needing to push content in one file (like a component or partial) into a place in another file.

While you can achieve a similar effect with Twig’s built-in {% block %} directive, Laravel’s Blade’s @push and @stack directives is far more versatile and functional, with no reliance on the template-extending syntax or order of the placements.

To bring this functionality to Twig, a colleague of mine, Chris Powell created the Twig Stack Extension package that works in pretty much the same way as Blade’s implementation.

For example, pushing into a named stack:

<!-- components/datepicker.twig -->
<input type="text" class="datepicker" />

{% pushonce 'scripts' %}
    <script src="/path/to/datepicker-lib.js" />
{% endpushonce %}

And rendering a named stack:

<!-- layout.twig -->
<html>
    <head>...</head>
    <body>
        ...
        {% stack 'scripts' %}
    </body>
</html>

You can get the package below.

Or see Chris’ post about why we created it and didn’t use an existing solution here:

Photo of Liam Hammett
written by
Liam Hammett
Found a typo? Suggest a fix here!
Hit me up on Twitter / GitHub / LinkedIn / email me
Copyright © 2025 Liam Hammett and all that kind of stuff