Twig Lexer Override for Special Situations

Update: This is coming from the mailing database, but i thought to replicate it because it is something very useful sometimes.
Credits to: Casey Klebba

You can use a custom Twig_Lexer this way:

in config.yml
———–

services:
    twig:
        class: Twig_Environment
        arguments: ['@twig.loader', %twig.options%]
        calls:
            - [addGlobal, ['app','@templating.globals']]
            - [setLexer, ['@custom.lexer']]
    custom.lexer:
        class: Acme\DemoBundle\Twig\CoreLexer
        arguments: ['@twig']

Then:

namespace Acme\DemoBundle\Twig;
 
use \Twig_Environment;
use \Twig_Lexer;
 
class CoreLexer extends Twig_Lexer {
 
    public function __construct(Twig_Environment $twig)
    {
        parent::__construct($twig, array(
            'tag_comment'   => array('{#', '#}'),
            'tag_block'     => array('{%', '%}'),
            'tag_variable'  => array('{{', '}}'),
            'interpolation' => array('#{', '}'),
        ));
    }
}

Very easy now!

–Casey

That is it. Enjoy! And thanks Casey.

Leave a Reply

Your email address will not be published. Required fields are marked *