Twig Composer
A callback function library for Twig: you will be able to execute code when templates are rendered., (*1)
Useful for calling code like controllers, etc. before the template is rendered. This can be
done in some frameworks as Symfony or Laravel, but this library works directly with Twig., (*2)
For example, if you have a menu.twig template which can be included in a layout, you can do:, (*3)
TwigComposer::getNotifier()->on('menu.twig', [$menuService,generateDinamicMenu]);
And then use the menu generated in menu.twig template. You won't need to include a call to
the service in each controller which uses the layout., (*4)
Getting Started
If you are using composer tool, you can start using TwigComposer requiring the library:, (*5)
require maceda/twig-composer
If not, please follow installation instructions., (*6)
To be notified of template renders, you need to indicate TwigComposer as the base class
for templates when creating Twig_Environment:, (*7)
$this->twig = new \Twig_Environment(
$loader,
array(
...
'base_template_class' => 'TwigComposer\TwigComposer',
...
));
To receive callbacks you must register them for each template you want to be notified:, (*8)
TwigComposer::getNotifier()->on('Template_I_Want_To_Watch', $callback);
$callback will be called each time 'Template_I_Want_To_Watch' is rendered., (*9)
You can also inherit your own base class from TwigComposer if you need to use your own base class for Twig (do not
forget to call parent methods when corresponding), (*10)
Installation
If you do not use composer, you must install and require the following dependencies:, (*11)
You must also include Relayer.php and TwigComposer.php in your project to use this library., (*12)
Running the tests
This library uses PHPUnit for test. To run the test, execute this command:, (*13)
/usr/bin/php ./vendor/phpunit/phpunit/phpunit ./tests
If you want to generate code coverage information, just add the option --coverage-html DIRECTORY, (*14)
Contributing
Feel free to contribute to this code. Please send an email to the authors and / or
a pull request to the project's repository: https://github.com/AlvaroMaceda/twig-composer, (*15)
Authors
License
This project is Public Domain., (*16)
Acknowledgments