symfony - 如果有条件,检查 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 %}
解决方案
您可以编写自己的测试来减少所需的Twig
代码量。这很简单,只需要两个步骤:
首先注册您
test
的twig
(直接或使用getTests
您的方法twig extension
$twig->addTest(new \Twig_SimpleTest('false', null, [ 'node_class' => '\MyProject\Twig\Node\FalseExpressionNode' ]));
创建测试
<?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
在调试模式下抑制任何未定义的变量消息
推荐阅读
- oracle - Oracle表单中更新主块主键列时需要更新明细块主键列
- php - delete() 在 laravel 8 控制器上不起作用
- logging - Keycloak ERROR_LOG 到日志文件
- angular - Ionic 6. 更新到 cordova 10.0.0 后 Google 地图未显示
- sql - 有没有办法为 FOR LOOP 动态设置 SELECT 查询
- css - 如何在摩纳哥编辑器中更改建议选项的高度
- html - 物化输入内的字体真棒图标
- python - 我不能在 Visual Studio Code 上使用“从数学导入 sqrt”
- c# - SpecFlow ISpecFlowOutputHelper 抛出 Unable to resolve service for type
- python - 如何在pymupdf python中保存循环文档