Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
361 views
in Technique[技术] by (71.8m points)

php - Use custom delimiters in the current Twig template

I use Twig to generate LaTeX documents. Twig's default delimiter syntax clashes badly with LaTeX's curly braces. Simply escaping LaTeX is no option as it makes the code completely unreadable. I know I can define custom delimiters globally, but I don't want to rewrite all of my HTML templates to use the new syntax.

I also know about verbatim sections but those make the code truly ugly:

ihead{
{% endverbatim %}
{{ title }}
{% verbatim %}
} 

Is there a way I can change the syntax for just the current template or a set of templates, something like:

{% set_delimiters({
    'tag_comment'  : ['<%#', '%>'],
    'tag_block'    : ['<%' , '%>'],
    'tag_variable' : ['<%=', '%>'],
    'interpolation': ['#<' , '>']
}) %}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As you can see, it's not recommanded to use this feature Customizing the Syntax

BTW here's a quick and easy example to explain how to use custom delimiters in symfony:

service.yml

services:
    templating_lexer:
        public: true
        parent: templating.engine.twig
        class:  AcmeYourBundleTwigTwigLexerEngine

TwigLexerEngine

namespace AcmeYourBundleTwig;

use SymfonyBundleTwigBundleTwigEngine;

class TwigLexerEngine extends TwigEngine
{
    public function setTwigLexer($lexer)
    {
         $this->environment->setLexer($lexer);

         return $this;
    }
}

Your controller

public function yourAction()
{
    $lexer = new Twig_Lexer($this->get('twig'), array(
        'tag_comment'  => array('{*', '*}'),
        'tag_block'    => array('{', '}'),
        'tag_variable' => array('{$', '}'),
    ));

    $templating = $this->get('templating_lexer');
    $templating->setTwigLexer($lexer);

    return $templating->renderResponse('YourBundle::template.html.twig');
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...