简体   繁体   English

Twig:默认情况下在Include上使用“Ignore Missing”

[英]Twig: Use “Ignore Missing” on Include by default

With Twig I am using {% include %} a lot. 使用Twig我经常使用{% include %} I need to attach ignore missing to every include, since I do not want to run into an Exception when a file is not found. 我需要将ignore missing附加到每个包含,因为我不希望在找不到文件时遇到异常。 This bloats the template code a lot and I am looking for an option to attach ignore default to all includes by default without repeating it with every include call. 这会使模板代码膨胀很多,我正在寻找一个选项, ignore defaultignore default附加到所有包含,而不会在每次包含调用时重复它。 I am looking for an equivalent of php's include in Twig since Twig's own include behaves like php's require. 我正在寻找一个相当于PHP的包含在Twig,因为Twig自己的包含行为像PHP的要求。

How can I include templates in Twig without having Exceptions thrown when a file is not found and without adding ignore missing to every single include? 如何在Twig中包含模板,而不会在找不到文件时抛出异常,并且不会在每个包含中添加ignore missing
I was looking for a config in Twig but did not find an option. 我在Twig寻找配置,但没有找到一个选项。

by over-riding built-in include 通过内置的覆盖包括

     class TokenParser_Include extends Twig_TokenParser
        {
            public function parse(Twig_Token $token)
            {
                $expr = $this->parser->getExpressionParser()->parseExpression();

                list($variables, $only, $ignoreMissing) = $this->parseArguments();

                return new Twig_Node_Include($expr, $variables, $only, $ignoreMissing = true, $token->getLine(), $this->getTag());
            }

            protected function parseArguments()
            {
                $stream = $this->parser->getStream();

                $ignoreMissing = false;
                if ($stream->nextIf(Twig_Token::NAME_TYPE, 'ignore')) {
                    $stream->expect(Twig_Token::NAME_TYPE, 'missing');

                    $ignoreMissing = true;
                }

                $variables = null;
                if ($stream->nextIf(Twig_Token::NAME_TYPE, 'with')) {
                    $variables = $this->parser->getExpressionParser()->parseExpression();
                }

                $only = false;
                if ($stream->nextIf(Twig_Token::NAME_TYPE, 'only')) {
                    $only = true;
                }

                $stream->expect(Twig_Token::BLOCK_END_TYPE);

                return array($variables, $only, $ignoreMissing);
            }

            public function getTag()
            {
                return 'include';
            }
        }

   $twig->addTokenParser(new TokenParser_Include());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM