eZ Community » Forums » Developer » Syntax for foreach with break
expandshrink

Syntax for foreach with break

Syntax for foreach with break

Saturday 04 June 2011 12:44:46 am - 4 replies

I need to run a foreach loop over an array of objects, test for class type (image) and then stop.... loop through until an image is found, output that image, stop looping.

It looks to me like foreach, break should do it. Does anybody have an example of the syntax required?

regards

paulb

Sunday 05 June 2011 12:23:05 am

Not exactly what you are looking for but it does use a break:

{if $this_node.data_map.image.content.is_valid}
    {*has an image in the image attribute*}
    <img src={$this_node.data_map.image.content.['medium'].url|ezroot} />
{elseif ne($this_node.object.related_contentobject_count,0)}
    {foreach $this_node.object.related_contentobject_array as $related_object}
        {if eq($related_object.class_identifier,"image")}
            {*has an image as a related object*}
            <img src={$related_object.data_map.image.content.['medium'].url|ezroot} />
            {break}
       {/if}
    {/foreach}
{else}
    {*got bubkis*}
    <img src={"dummy.jpg"|ezimage}>
{/if}

Sunday 05 June 2011 12:47:05 pm

Hi Paul

You can use the {break} command for that, as suggested in Steven's snippet.

Take a look at the foreach reference doc for more info blunk.gif Emoticon.

Sunday 05 June 2011 2:01:47 pm

Thanks Steven, That works well and was what I was looking for. Thanks too Jérôme. The documentation is a bit vague about how to use {break}, but now I understand. If only I could add a comment to the documentation so others could see what I've been shown... 

Wednesday 12 October 2011 5:19:46 pm

What would be the best way to break 2 foreach in a ez templates ?

Similar to the following PHP code (very simple here, more complex in my template)

 foreach($loop1 as $a){
    foreach($loop2 as $b){
        break 2;
    }
}

I did something like that:

{def $needToBreak = 0}
{foreach $loop1 as $a}
    {foreach $loop2 as $b}
         {set $needToBreak = 1}
         {break}
    {/foreach}
    {if eq( $needToBreak , 1 )}
        {break}
    {/if}
{/foreach}

But here I need to define an extra variable and check the if statement for each loop1 element....

Thanks for the help if you know a better solution happy.gif Emoticon

Modified on Wednesday 12 October 2011 5:20:17 pm by Laurent Dorier

expandshrink

You must be logged in to post messages in this topic!

36 542 Users on board!

Forums menu

Proudly Developed with from