Fog Creek Software
Fog Creek Software

CityDesk 2.0-Documentation
Dealing With Missing Fields

Neuschwanstein CastleSometimes you want to create a template which looks different depending on which fields are filled in. For example, a real-estate listing site might want to display pictures of the homes for sale if they are available, and automatically substitute in a picture of Neuschwanstein Castle otherwise. This can be done with if blocks.

Suppose you had the following simple template:

<html>
<head><title>{$ .headline $}</title></head>
<body>
    <h1>All About {$ .headline $}</h1>
    {$ .body $}
</body>
</html>

If the article contains a headline, say, Monkeys, and a body, say, Monkeys are our friends, this will display exactly as expected:

<html>
<head><title>Monkeys<title></head>
<body>
    <h1>All About Monkeys</h1>
    Monkeys are our friends
</body>
</html>

But if an article doesn't contain a headline, you get:

<html>
<head><title><title></head>
<body>
    <h1>All About </h1>
    Monkeys are our friends
</body>
</html>

The lack of a title is a problem, and having "All About" as the heading is a little bit ugly. This can be solved by using the if blank or if nonblank blocks to detect missing fields and do something differently. The syntax of the if block is:

{$ if blank .field $}
conditional-text
{$ endIf $}

or:

{$ if nonblank .field $}
conditional-text
{$ endIf $}

In the first case, everything inside the block (conditional-text) is displayed if, and only if, the field is blank. In the second case, everything inside the block is displayed if the field is not blank. So we can fix our template as follows:

<html>
<head>
    <title>
        {$ if blank .headline $}
            Another Article
        {$ endif $}
        {$ if nonblank .headline $}
            {$ .headline $}
        {$endIf$}
    </title>
</head>
<body>
    <h1>
        {$ if blank .headline $}
            Another Anonymous Article
        {$ endIf $}
        {$ if nonblank .headline $}
            All About {$ .headline $}
        {$endIf$}
   
</h1>
    {$ .body $}
</body>
</html>

You can use if with any variable name or field name. You can even use it inside a loop:

{$foreach x in (all)$}
    {$x.headline$}
    {$ if nonblank x.sidebar $}
        With Sidebar!
    {$endIf$}
    {$ if blank x.sidebar $}
        No Sidebar on this one.
    {$endIf$}
    <br>
{$next$}

 

CityDesk Documentation -  Home


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