Skip to content

Instantly share code, notes, and snippets.

@seamusleahy
Last active April 16, 2018 14:05
Show Gist options
  • Save seamusleahy/36c8737efc057704a2cd to your computer and use it in GitHub Desktop.
Save seamusleahy/36c8737efc057704a2cd to your computer and use it in GitHub Desktop.
Twig tag to remove indentation at the start of each line: {% indentless %}...{%endindetless %}
<?php
/**
* Remove whitespace at the start of each line.
*
* Based on Twig's Twig_TokenParser_Spaceless class
*/
class TwigIndentlessTokenParser extends Twig_TokenParser
{
/**
* Parses a token and returns a node.
*
* @param Twig_Token $token A Twig_Token instance
*
* @return Twig_NodeInterface A Twig_NodeInterface instance
*/
public function parse(Twig_Token $token)
{
$lineno = $token->getLine();
$this->parser->getStream()->expect(Twig_Token::BLOCK_END_TYPE);
$body = $this->parser->subparse(array($this, 'decideIndentlessEnd'), true);
$this->parser->getStream()->expect(Twig_Token::BLOCK_END_TYPE);
return new TwigIndentlessNode($body, $lineno, $this->getTag());
}
public function decideIndentlessEnd(Twig_Token $token)
{
return $token->test('endindentless');
}
/**
* Gets the tag name associated with this token parser.
*
* @return string The tag name
*/
public function getTag()
{
return 'indentless';
}
}
/**
* Represents an indentless node.
*
* Based on Twig's Twig_Node_Spaceless class
*/
class TwigIndentlessNode extends Twig_Node
{
public function __construct(Twig_NodeInterface $body, $lineno, $tag = 'indentless')
{
parent::__construct(array('body' => $body), array(), $lineno, $tag);
}
/**
* Compiles the node to PHP.
*
* @param Twig_Compiler $compiler A Twig_Compiler instance
*/
public function compile(Twig_Compiler $compiler)
{
$compiler
->addDebugInfo($this)
->write("ob_start();\n")
->subcompile($this->getNode('body'))
->write("echo trim(preg_replace('/^[ \t]+/m', '', ob_get_clean()));\n");
}
}
<?php
$twig = new Twig_Environment($loader);
$twig->addTokenParser(new TwigIndentlessTokenParser());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment