在当前的Twig模板中使用自定义分隔符 [英] Use custom delimiters in the current Twig template

查看:158
本文介绍了在当前的Twig模板中使用自定义分隔符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用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.

我也了解 verbatim部分,但是这些使代码看起来非常丑陋:

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:  Acme\YourBundle\Twig\TwigLexerEngine

TwigLexerEngine

namespace Acme\YourBundle\Twig;

use Symfony\Bundle\TwigBundle\TwigEngine;

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆