Define your own Twig tag (copy and paste method)
You can define your own Twig spacelessblock tag that combines block and spaceless . Then you can use {% spacelessblock xyz %}โฆ{% endspacelessblock %} in your templates. Here's how you do it fast and dirty (copy and paste).
New Twig node
First, define the Twig_Node_SpacelessBlock class (for example, in the Extension directory of your package):
class Twig_Node_SpacelessBlock extends \Twig_Node_Block { public function __construct($name, Twig_NodeInterface $body, $lineno, $tag = null) { parent::__construct(array('body' => $body), array('name' => $name), $lineno, $tag); } public function compile(Twig_Compiler $compiler) {
New Twig Token Analyzer
Our new Twig node should be created anywhere when Twig finds {% spacelessblock xyz %} in the template. To do this, we need a parser marker, which we call Twig_TokenParser_SpacelessBlock . We basically copy and paste Twig_TokenParser_Block :
class Twig_TokenParser_SpacelessBlock extends \Twig_TokenParser { public function parse(Twig_Token $token) { // โฆ $this->parser->setBlock($name, $block = new Twig_Node_SpacelessBlock($name, new Twig_Node(array()), $lineno)); // โฆ } public function decideBlockEnd(Twig_Token $token) { return $token->test('endspacelessblock'); } public function getTag() { return 'spacelessblock'; } }
Tell us about it Twig
In your extension class:
class Extension extends \Twig_Extension { public function getTokenParsers() { return array( new Twig_TokenParser_SpacelessBlock(), ); } }
Report this to Symfony
If not already done, add the following to your services.yml :
services: # โฆ my.extension: class: Acme\MyBundle\Extension\Extension tags: - { name: twig.extension }
Best alternatives
Preprocessor
It is best to use a preprocessor to simply replace
{% spacelessblock xyz %} โฆ {% endspacelessblock %}
{% block xyz %}{% spaceless %} โฆ {% endspaceless %}{% endblock %}
which reuses all the code that has already been recorded in the Twig project, including possible changes.