简体   繁体   中英

Object variable don't display in a twig template

I find this strange behaviour when using Twig (v1.23.3)

In a templace I have an array of objects : I use the dump function to display it, like this :

<pre align="left" style="text-align: left; font-size: 80%">
{{ dump(current_balances) }}
</pre>
{% for key, val in current_balances %}
    {{ val.name }} : {{ val.balance | number_format(2, '.', ' ') }} €<br>
{% else %}
    Aucun solde trouvé.
{% endfor %}

The output of dump is as expected :



      array(2) {
      [0]=>
      object(Record)#20 (3) {
        ["name"]=>
        string(32) "Bank 1 - Account"
        ["balance"]=>
        string(7) "2000.00"
      }
      [1]=>
      object(Record)#21 (3) {
        ["name"]=>
        string(32) "Bank 2 - Account"
        ["balance"]=>
        string(8) "1000.00"
      }
    }

But the output of the for loop is not correct. {{ val.name }} is displayed, but {{ val.balance }} is empty.

I dit this kind of loops hundreds of time - this code is merely cut-and-paste from a template that works.

Event more curious is that, if I invert the order of the vars in the object (as is it matters), putting balance before name, then balance is displayed, and not name !

Don't really know where to look with this one. Of course, my template are rendered with controllers calling models, so this is only a little part of the code.

I think I found a bug, similar to Variables not replaced in Twig template but it's hard to tell.

That's not a bug ! I finally enable the cache in Twig and looked at the resulting code. Guess what ? Some non-printable char has find its way near the val.balance. A "cat -A" on the template file shows this :

{{ val.name }} : {{M-BM- val.balance }} M-bM-^BM-,<br>$

And result in this in the compiled template :

$this->getAttribute((isset($context[" val"]) ? $context[" val"] : null)

Noticed the space before val ?

Lost one hour with this one. Source problem is an obsolete frenck keymap in Debian....

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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