There is a common need to conditionally include/exclude an attribute in HTML tag:

    <ul id="menu">
        <li><a href="">Menu choice 1</a></li>
        <li><a href="" class="selected">Menu choice 2</a></li>
        <li><a href="">Menu choice 3</a></li>
        <li><a href="">Menu choice 4</a></li>
    </ul>

If you do it using Loop component, the template will look like this:

    <ul id="menu">
        <t:loop source="menuItems" value="menuItem">
            <li><a href="" class="${cssClass}">${menuItem}</a></li>
        </t:loop>
    </ul>

And in the component class:

    public String getCssClass() {
        return (menuItem.equals(currentMenuItem)) ? "selected" : null;
    }

The trick here is the null value returned. Tapestry will not render an attribute if its value is null.

In our case, the class attribute will be rendered only for the selected menu item (exactly what we need).

  • No labels