Skip to content

Introduce a Loop object#4131

Merged
fabpot merged 1 commit into
twigphp:4.xfrom
fabpot:loop-improvment
Jul 11, 2024
Merged

Introduce a Loop object#4131
fabpot merged 1 commit into
twigphp:4.xfrom
fabpot:loop-improvment

Conversation

@fabpot

@fabpot fabpot commented Jul 9, 2024

Copy link
Copy Markdown
Contributor

Fixes #4096

Comment thread doc/tags/for.rst Outdated
Comment thread src/Runtime/Loop.php Outdated
Comment thread src/Runtime/Loop.php
Comment thread src/Runtime/Loop.php Outdated
Comment thread src/Runtime/Loop.php Outdated
@fabpot fabpot force-pushed the loop-improvment branch 5 times, most recently from a77bad8 to 22071a3 Compare July 9, 2024 16:36
Comment thread doc/tags/for.rst Outdated
implement the ``Countable`` interface.
When the underlying PHP iterator is not countable, the ``loop.length``,
``loop.revindex``, ``loop.revindex0``, and ``loop.last`` variables are not
available and a ``RuntimeException`` is thrown if you retry to use them.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
available and a ``RuntimeException`` is thrown if you retry to use them.
available and a ``RuntimeException`` is thrown if you try to use them.

Comment thread src/Runtime/Loop.php
@fabpot fabpot changed the title [WIP] Introduce a Loop object Introduce a Loop object Jul 10, 2024
@fabpot fabpot force-pushed the loop-improvment branch from 22071a3 to 6e3b098 Compare July 11, 2024 05:59
@fabpot fabpot force-pushed the loop-improvment branch from 6e3b098 to 17ef0be Compare July 11, 2024 06:03
@fabpot fabpot merged commit d1a13da into twigphp:4.x Jul 11, 2024
@fabpot fabpot deleted the loop-improvment branch July 11, 2024 06:04
@stof

stof commented Jul 11, 2024

Copy link
Copy Markdown
Member

I just realized that by using a Loop object, assigning it to a different variable (like outer_loop will now work fine, making it much easier to reference the loop context of an outer loop when using nested loops (especially when the number of nested loops can change) because it removes the need for loop.parent.loop.parent.loop:

{% for item in items %}
    {% set outer_loop = loop %}
    {% for property in item.properties %}
        {% for values in property.values %}
            {{ outer_loop.index0}} {{property.name}} {{loop.index0}}: {{value}}
        {% endfor %}
    {% endfor %}
{% endfor %}

And this makes it more similar to the way loops work in Jinja (this code snippet would also be valid Jinja code, while loop.parent is not)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Development

Successfully merging this pull request may close these issues.

2 participants