b1gw0rm - 6 months ago

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.

Answer

ryanthompson - 6 months ago

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

ryanthompson - 6 months ago

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

edster - 6 months ago

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

mitch - 4 days 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 - 4 days 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 - 4 days ago

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