在当前 Twig 模板中使用自定义分隔符 [英] Use custom delimiters in the current Twig template
问题描述
我使用 Twig 生成 LaTeX 文档.Twig 的默认分隔符语法与 LaTeX 的花括号严重冲突.简单地转义 LaTeX 是不行的,因为它会使代码完全不可读.我知道我可以全局定义自定义分隔符,但我不我不想重写我所有的 HTML 模板以使用新语法.
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': ['#<' , '>']
}) %}
推荐答案
如您所见,不建议使用此功能 自定义语法
As you can see, it's not recommanded to use this feature Customizing the Syntax
顺便说一句,这里有一个快速简单的例子来解释如何在 symfony 中使用自定义分隔符:
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;
}
}
您的控制器
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');
}
这篇关于在当前 Twig 模板中使用自定义分隔符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!