Last active
April 3, 2019 09:41
-
-
Save TiGR/5002699 to your computer and use it in GitHub Desktop.
Just an example how you could strip spaces before all (well, almost) control structures. See: https://github.com/TiGR/twig-preprocessor
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$loader = new Twig_Loader_Preprocessor(new Twig_Loader_Filesystem('tpl'), | |
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); | |
}); | |
$twig = new Twig_Environment($loader, array('cache' => 'cache/tpl')); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Twig Preprocessor loader that allows adding custom text filters for template | |
* strings. | |
* | |
* @package Twig | |
* @author Igor Tarasov <tarasov.igor@gmail.com> | |
*/ | |
class Twig_Loader_Preprocessor implements Twig_LoaderInterface, Twig_ExistsLoaderInterface { | |
private $realLoader, $callback; | |
/** | |
* Constructor | |
* | |
* @param Twig_LoaderInterface $loader loader that does real loading of templates | |
* @param callable $callback processing callback that should accept template | |
* string as the only parameter and return the result | |
*/ | |
public function __construct(Twig_LoaderInterface $loader, callable $callback) | |
{ | |
$this->realLoader = $loader; | |
$this->callback = $callback; | |
} | |
/** | |
* {@inheritdoc} | |
*/ | |
public function getSource($name) | |
{ | |
return call_user_func($this->callback, $this->realLoader->getSource($name)); | |
} | |
/** | |
* {@inheritdoc} | |
*/ | |
public function exists($name) | |
{ | |
if ($this->realLoader instanceof Twig_ExistsLoaderInterface) { | |
return $this->realLoader->exists($name); | |
} | |
return true; | |
} | |
/** | |
* {@inheritdoc} | |
*/ | |
public function getCacheKey($name) | |
{ | |
return $this->realLoader->getCacheKey($name); | |
} | |
/** | |
* {@inheritdoc} | |
*/ | |
public function isFresh($name, $time) | |
{ | |
return $this->realLoader->isFresh($name, $time); | |
} | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Version for both twig versions 1 and 2: https://github.com/TiGR/twig-preprocessor