简体   繁体   English

在关联数组的Twig问题上需要帮助

[英]Need help on a Twig issue with associative arrays

My controller sends to Twig the following associative array in a variable called 'petition'; 我的控制器将以下关联数组发送到Twig中,该数组称为“重复”变量;

Array
(
    [0] => stdClass Object
        (
            [id] => 1
            [doctype] => "somedoc"
            [nrdoc] => "99"
            [datadoc] => "2015-01-01"
        )
    [1] => stdClass Object
        (
            [id] => 2
            [doctype] => "otherdoc"
            [nrdoc] => "100"
            [datadoc] => "2015-01-01"
        )
)

Then, in my Twig template (view) I'm doing this: 然后,在我的Twig模板(视图)中,我正在这样做:

    {% for id in petition %}

        {% if id.doctype == 'somedoc' %}
            {{id.nrdoc}} / {{id.datadoc}}
        {% else %}
                UNDEFINED!
        {% endif %}

    {% endfor %}

The problem is that I can't figure out the logic of how to output "UNDEFINED!" 问题是我无法弄清楚如何输出“未定义!”的逻辑。 only once, if the doctype != "somedoc" when there are other key->value elements in the array. 如果数组中还有其他key-> value元素,则如果doctype!=“ somedoc”仅一次。 The way I'm doing it, it will output "UNDEFINED!" 我这样做的方式,它将输出“未定义!” everytime the script loops... 每当脚本循环...

Thank you in advance for your help 预先感谢您的帮助

Gabriel 加布里埃尔

One variant is to define an extra variable for this: 一种变体是为此定义一个额外的变量:

{% set undefined = false %}

{% for id in petition %}
    {% if id.doctype == 'somedoc' %}
        {{ id.nrdoc }} / {{ id.datadoc }}
    {% else %}
        {% set undefined = false %}
    {% endif %}
{% endfor %}

{% if undefined == true %}
    UNDEFINED!
{% endif %}

You can read more about setting Twig variables here . 您可以在此处阅读有关设置Twig变量的更多信息。

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

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