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



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

我也知道逐字部分,但这些使代码非常丑陋:

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

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

{% set_delimiters({
    'tag_comment'  : ['<%#', '%>'],
    'tag_block'    : ['<%' , '%>'],
    'tag_variable' : ['<%=', '%>'],
    'interpolation': ['#<' , '>']
}) %}

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

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

服务.yml

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

树枝词法学引擎

namespace AcmeYourBundleTwig;
use SymfonyBundleTwigBundleTwigEngine;
class TwigLexerEngine extends TwigEngine
{
    public function setTwigLexer($lexer)
    {
         $this->environment->setLexer($lexer);
         return $this;
    }
}

您的控制器

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');
}

最新更新