Skip or continue in a Velocity format

Ashley Williams's Avatar

Ashley Williams

11 Feb, 2013 04:50 PM

Hi there,

I was wondering if there was a way to somehow skip an item in a foreach loop when it doesn't meet a certain criteria? Right now I have one of my formats set up to where if the post is past a certain date chosen by the user, then it will skip that post (it will do nothing). I'm only displaying 10 posts at most, but if one of those posts is expired then it will only display 9 (instead of displaying the next post that meets the criteria).

Here's a simplified version of what I have:

#foreach($story in $pagesInCat)
    #set($data = $story.getChild("system-data-structure"))                               
    ## Archive only date
    #set ($archive-date = "")
    #set ($archive-date = $_DateTool.getDate($data.getChild("archive-only-date").value))
    #set ( $today = $_DateTool.getDate() )      
                                
    #if ( $_DateTool.difference($today, $archive-date).getSeconds() <= 0  )
            Do nothing and go to the next item.
    #else
                <li>Here's the post!</li> 
        #end                           
        #if ($count == 10)
        #break
        #end
#end
  1. 1 Posted by Ryan Griffith on 11 Feb, 2013 07:49 PM

    Ryan Griffith's Avatar

    Hi Ashley,

    I have not come across a continue directive. I would recommend reversing your #if statement so you don't need the additional else. Perhaps something like:

    #set ( $today = $_DateTool.getDate() )   
    #set ( $count = 0 ) 
    #foreach( $story in $pagesInCat )
        ## Archive only date
        #set ( $archive-date = "" )
        #set ( $archive-date = $_DateTool.getDate($data.getChild("archive-only-date").value) )
    
        #if ( $_DateTool.difference($today, $archive-date).getSeconds() > 0  )
            #set( $data = $story.getChild("system-data-structure") )
            ## Code here.
            
            #set ( $count = $count + 1 )
        #end
    
         #if ( $count == 10 )
            #break
        #end
    #end
    

    Note: I made a few adjustments to make things a bit more efficient, such as defining the $today variable outside of the loop since that won't change and grabbing the Page's structured data only if we land inside of the conditional.

    Please let me know if you have any questions.

    Thanks

  2. Ryan Griffith closed this discussion on 18 Feb, 2013 02:11 PM.

Comments are currently closed for this discussion. You can start a new one.

Keyboard shortcuts

Generic

? Show this help
ESC Blurs the current field

Comment Form

r Focus the comment reply box
^ + ↩ Submit the comment

You can use Command ⌘ instead of Control ^ on Mac