We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Passing loop context to macro / partial as argument

Hi there,

I'm trying to use a loop context as an argument for partial, but it does not seem to get passed in (nor for macros):

        {% for hop in item.getOutboundHops() %}
            {{ partial('private/flight_hop',{'loop':loop,'hop':hop}) }}
        {% endfor %}

I get no error message, but the loop properies are always empty. I've also tried assigning it to a variable, to no avail:

        {% for hop in item.getOutboundHops() %}
            {% set l = loop %}
            {{ partial('private/flight_hop',{'loop':l,'hop':hop}) }}
        {% endfor %}

Could someone give a hint, so I don't have to pass in the context properties as seperate arguments?

Thanks!



34.6k
Accepted
answer

The loopcontext is only generated when a member of loop is accesed, as no members are accessed then this variable is not generated.

I've checked the generated php file, too bad :)

{% set l = loop.index %}
{% set l = loop %}

translates to:

<?php $l = $v73334171036986186031loop->index; ?>
<?php $l = $loop; ?>

I guess even if a context property is accessed, the parser still needs an accessor to properly evaluate it to the temprorary stdClass. Might file a feature request and a fork in the future, by adding a loop.get or some similar property to the stdClass which returns the temporary class. I think it would be really useful, especially since nested blocks aren't supported.

Thanks Andres, all the best!