Skip to content

Instantly share code, notes, and snippets.

@TiGR
Last active April 3, 2019 09:41
Show Gist options
  • Save TiGR/5002699 to your computer and use it in GitHub Desktop.
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
<?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'));
<?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);
}
}
?>
@TiGR
Copy link
Author

TiGR commented Apr 3, 2019

Version for both twig versions 1 and 2: https://github.com/TiGR/twig-preprocessor

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment