在当前的Twig模板中使用自定义分隔符

Bot*_*ázs 7 php symfony twig

我使用Twig生成LaTeX文档.Twig的默认分隔符语法与LaTeX的花括号发生严重冲突.简单地转义LaTeX是没有选择的,因为它使代码完全不可读.我知道我可以全局定义自定义分隔符,但我不想重写所有HTML模板以使用新语法.

我也知道逐字节,但那些使代码真的很难看:

\ihead{
{% endverbatim %}
{{ title }}
{% verbatim %}
} 
Run Code Online (Sandbox Code Playgroud)

有没有办法可以更改当前模板或一组模板的语法,如:

{% set_delimiters({
    'tag_comment'  : ['<%#', '%>'],
    'tag_block'    : ['<%' , '%>'],
    'tag_variable' : ['<%=', '%>'],
    'interpolation': ['#<' , '>']
}) %}
Run Code Online (Sandbox Code Playgroud)

a.a*_*dad 4

如您所见,不建议使用此功能自定义语法

顺便说一句,这里有一个快速简单的示例来解释如何在 symfony 中使用自定义分隔符:

服务.yml

services:
    templating_lexer:
        public: true
        parent: templating.engine.twig
        class:  Acme\YourBundle\Twig\TwigLexerEngine
Run Code Online (Sandbox Code Playgroud)

TwigLexer引擎

namespace Acme\YourBundle\Twig;

use Symfony\Bundle\TwigBundle\TwigEngine;

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

         return $this;
    }
}
Run Code Online (Sandbox Code Playgroud)

你的控制器

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');
}
Run Code Online (Sandbox Code Playgroud)