In this episode, we dive into creating our very own helper function for Twig so we can easily fetch configuration data right inside our templates. We start by outlining our goal: making it super convenient to output data from the app's config, like displaying the app's name in your Twig templates. The idea is you should be able to do something like config.get('app.name')
in Twig, and have it always be up-to-date if you change it in your setup.
To do this, we go through the process of registering custom Twig functions by using a runtime loader. We build a couple of new classes—a TwigRuntimeLoader
that takes care of instantiating our runtime extension with the necessary dependencies (like the service container), and a TwigRuntimeExtension
that actually holds all our custom helper methods.
We wire it all up in the service provider, connect everything together, and then try it out in our Twig templates. At first, we create a dummy function that just returns 'no framework', but then quickly update it so it pulls the real value from the config. We also refactor it so instead of a name
function, we build a more general-purpose config
function—making our templates super flexible!
Towards the end, we show how you can easily add more helpers by just making new methods in the extension and mapping them up in your custom Twig extension. That way, you can expose anything to Twig in just a few steps. Basically, after this episode, you'll have a much easier time getting your app's PHP services and data into your Twig templates!