Injecting Custom PHP Into Twig
Created 3 years ago by b1gw0rm

What 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.

ryanthompson  —  3 years ago Best Answer

php artisan make:addon 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:

edster  —  3 years ago

That should be handled via a addon or some other method, with the array passed to the view and parsed with twig.

mitch  —  2 years ago

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.

ryanthompson  —  2 years ago

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!

ryanthompson  —  2 years ago

And your plugin class would extend the streams platform plugin class.