tigr / twig-preprocessor
This very simple loader adds a way to pre parse twig files before loading them into twig parser
Installs: 37 198
Dependents: 0
Suggesters: 0
Security: 0
Stars: 2
Watchers: 2
Forks: 3
Open Issues: 0
Requires
- php: >=7.0
- twig/twig: ^2.0|^3.0
Requires (Dev)
- phpunit/phpunit: ^5.7
- satooshi/php-coveralls: ~0.6
README
This Twig Preprocessor loader allows you to do custom manipulations with twig templates before passing them to twig parser. This allows you, for instance, to do some substitutions, or format templates to make them look better.
This branch (master) contains code for Twig 2.x.
Installation
Installation via composer (version for twig 2):
composer require tigr/twig-preprocessor
If you want to use it with twig 1, use version 1:
composer require tigr/twig-preprocessor "~1.0"
Usage
In general usage, you pass real template loader to Twig Preprocessor Loader and also a callback that would be called to mingle with twig template code. So, general usage is this:
$realLoader = Twig_Loader_Filesystem('/path/to/templates'); $loader = Twig_Loader_Preprocessor( $realLoader, function($twigSource) { // do something with $twigSource return $twigSource; } ); $twig = new Twig_Environment($loader);
The main reason why this code was written was to make Twig output a bit more pretty-formatted code. You can read more about this in this Twig issue.
In short, the idea is to remove all spaces/tabs before any (well, most) twig control structures. Here is how you can achieve this:
$loader = new Twig_Loader_Preprocessor( $realLoader, function ($template) { static $regExp; // the RE isn't perfect, it won't match structures having curly braces within, // but it's okay for me. if (!isset($regExp)) { $regExp = str_replace( ['_', '{', '}'], ['[\t ]*', '\{', '\}'], '/^_({([#%])[^}]*[^-](?2)}|{%_block_\w*_%}{%_endblock_%})$/m' ); } return preg_replace($regExp, '$1', $template); } );