Injecting Custom PHP Into Twig
Created 7 years ago by b1gw0rmWhat would be the best practice for injecting a piece of custom PHP code into a template via Twig? For a contrived example, let's say I have a simple piece of php code that reads in some basic weather data from a rest API, converts it to and array and then need to display it on an inside page template via Twig.
On that linked page, it says to add the extension to the twig environment. While it looks like the generated Plugin.php has a method initRuntime(Twig_Environment $environment)
where you might use $environment->addExtension(new Project_Twig_Extension());
, I could not get that to work or find anywhere where that initRuntime is called. Just throw it in the getFunctions()
method. Hopefully this will save someone else a little bit of time.
The service provider classes for Pyro addons have a $plugins
array property that you can add your plugin class to and it will be added automatically. Sorry I omitted that detail!
And your plugin class would extend the streams platform plugin class.
php artisan make:addon b1gworm.plugin.weather
then you can create a function to do it like{{ weather() }}
Plugins are basically Twig extensions. You can kinda take info from here on defining how a function for example works - then just use commands and pyro stuff to handle the lifting: https://twig.symfony.com/doc/2.x/advanced.html#creating-an-extension