Lack of interest Implement break for foreach in templates

This suggestion has been closed automatically because it did not receive enough votes over an extended period of time. If you wish to see this, please search for an open suggestion and, if you don't find any, post a new one.

Snog

Well-known member
I did a search and didn't find anything about this, so here we are...

It would be nice to be able to break out of a foreach loop in templates.

Consider this oversimplified example where $loopArray might have 100 entries...
Code:
<xf:foreach loop="$loopArray" value="$loopValue">
    <xf:if is="$loopValue.value == 1">
        ...Some code...
    </xf:if>
</xf:foreach>
In the above, the first item is the one that would be processed, but the foreach loop continues through all 100 entries (remember this is oversimplified).

The addition of a break from the foreach would speed processing simply by not processing the other 99 entries...
Code:
<xf:foreach loop="$loopArray" value="$loopValue">
    <xf:if is="$loopValue.value == 1">
        ...Some code...
        <xf:break/>
    </xf:if>
</xf:foreach>

Again, this is oversimplified for clarity and not intended as a working example.
 
Upvote 3
This suggestion has been closed. Votes are no longer accepted.
I don't know the underlying lexer code, but <xf:foreach loop="$loopArray" value="$loopValue" if="$loopArray.value == 1"> also works. Whether it's simply a shortcut to what's already in your example or what I don't know, just thought I'd mention it :)
 
I don't know the underlying lexer code, but <xf:foreach loop="$loopArray" value="$loopValue" if="$loopArray.value == 1"> also works. Whether it's simply a shortcut to what's already in your example or what I don't know, just thought I'd mention it :)
I gave that a try and it executes the "Some code" with each iteration of the foreach. Note that the $loopValue.value can be 1 more than once, but "Some code" should only execute once.

When I said it's over simplified, that's what I meant. The less simplified version uses a "set" and checks if the set value is 1 or 0 to stop the "Some code" from executing with each iteration. But it can't stop the foreach from going through all 99 other $loopArray values.
Code:
<xf:set var="$found" value="0" />
<xf:foreach loop="$loopArray" value="$loopValue">
    <xf:if is="$loopValue.value == 1 && !$found">
        ...Some code...
        <xf:set var="$found" value="1" />
    </xf:if>
</xf:foreach>
 
Last edited:
Sorry to bubble up an old thread, but would love the ability to specify a break in foreach loop as well. Once the key/value I'm looking for is found, call it a day :)
 
Back
Top Bottom