Twig: in_array 或 if 语句中的类似内容? [英] Twig: in_array or similar possible within if statement?
本文介绍了Twig: in_array 或 if 语句中的类似内容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我使用 Twig 作为模板引擎,我真的很喜欢它.但是,现在我遇到的情况肯定必须以比我发现的更简单的方式来完成.
I am using Twig as templating engine and I am really loving it. However, now I have run in a situation which definitely mustbe accomplishable in a simpler way than I have found.
我现在拥有的是:
{% for myVar in someArray %}
{% set found = 0 %}
{% for id, data in someOtherArray %}
{% if id == myVar %}
{{ myVar }} exists within someOtherArray.
{% set found = 1 %}
{% endif %}
{% endfor %}
{% if found == 0 %}
{{ myVar }} doesn't exist within someOtherArray.
{% endif %}
{% endfor %}
我正在寻找的东西更像是这样的:
What I am looking for is something more like this:
{% for myVar in someArray %}
{% if myVar is in_array(array_keys(someOtherArray)) %}
{{ myVar }} exists within someOtherArray.
{% else %}
{{ myVar }} doesn't exist within someOtherArray.
{% endif %}
{% endfor %}
有没有一种方法可以实现我还没有见过的?
Is there a way to accomplish this which I haven't seen yet?
如果我需要创建自己的扩展,如何在测试函数中访问 myVar?
If I need to create my own extension, how can I access myVar within the test function?
感谢您的帮助!
推荐答案
您只需要将第二个代码块的第二行从
You just have to change the second line of your second code-block from
{% if myVar is in_array(array_keys(someOtherArray)) %}
到
{% if myVar in someOtherArray|keys %}
in is the containment-operator and keys a filter that returns an arrays keys.
这篇关于Twig: in_array 或 if 语句中的类似内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文