Injecting Custom PHP Into Twig

b1gw0rm - 3 weeks 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 - 3 weeks 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 - 3 weeks 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 - 3 weeks ago

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