首页 > 解决方案 > 如果有条件,检查 Twig 中多个变量的定义值和布尔值

问题描述

是否有一种更优雅的方法来检查 Twig 中的变量是否既已定义(可以安全引用/使用)又检查布尔值,就像我在下面所做的那样?

我有许多 Twig 模板,其中的逻辑很混乱,我希望它更具可读性,但是我不知道在 Twig 中这是如何完成的。

{% if primaryMethod is defined and paymentInProgress is defined and transactions is defined and not primaryMethod and not paymentInProgress and not transactions %}

标签: symfonytwiglogicsymfony-2.8templating-engine

解决方案


您可以编写自己的测试来减少所需的Twig代码量。这很简单,只需要两个步骤:

  1. 首先注册您testtwig(直接或使用getTests您的方法twig extension

    $twig->addTest(new \Twig_SimpleTest('false', null, [ 'node_class' => '\MyProject\Twig\Node\FalseExpressionNode' ]));

  2. 创建测试

    <?php
    namespace MyProject\Twig\Node;
    
    class FalseExpressionNode extends \Twig_Node_Expression_Test_Defined {
        public function compile(\Twig_Compiler $compiler)
        {
            $compiler->subcompile($this->getNode('node'))
                     ->raw('&& $context[\''.$this->getNode('node')->getAttribute('name').'\'] === false');
        }
    }
    

然后你可以在里面使用你的测试twig

{% if primaryMethod is false and paymentInProgress is false and transactions is false %}

旁注:测试FalseExpressionNode扩展Twig_Node_Expression_Test_Defined是为了twig在调试模式下抑制任何未定义的变量消息


推荐阅读