Fog Creek Software
Fog Creek Software

CityDesk 2.0-Documentation
Alternate Text for Empty Loops

Using the {$ else $} section in a forEach loop, you can provide an alternative which is displayed if the contents of the loop would otherwise be empty. For example, consider the following HTML code, which is designed to list all the headlines (from the headline folder) which were published today.

<p>Today's Headlines:</p>
{$ foreach x in (and (folder "headlines") (publishDate)) $}
    <p><a href="{$x.link$}">{$ x.headline $}</a></p>
{$ next $}

On a normal day where there are three new headlines, they will be listed, just as expected. But what happens if, one day, there are no new headlines? Then you would see this:

Today's Headlines:

... followed by nothing. People who visit your site will think it's an error. This is exactly what the else section is designed for. Modifying the code from above a little bit:

<p>Today's Headlines:</p>
{$ foreach x in (and (folder "headlines") (publishDate)) $}
    <p><a href="{$x.link$}">{$ x.headline $}</a></p>
{$ else $}
    <p>There are no headlines today.</p>
{$ next $}

This will produce

Today's Headlines:

There are no headlines today.

That's a little bit better, but still not perfect. We can combine the else section with the before section:

{$ foreach x in (and (folder "headlines") (publishDate)) $}
    <p><a href="{$x.link$}">{$ x.headline $}</a></p>
{$ before $}
    <p>Today's Headlines:</p>
{$ else $}
    <p>There are no headlines today.</p>
{$ next $}

Because the before section is only included if there is at least one matching article, when there are no articles, users will see only:

There are no headlines today.

 

CityDesk Documentation -  Home


©Copyright 2001-2003 Fog Creek Software, Inc. All Rights Reserved.