Extending the If Component

Extending the If Component

The If component can be made very flexible; its main parameter, test, does not have to be bound to a boolean value, it merely has to be bound to a value that can be coerced to boolean.

For example, you may be working on an application that does a lot of Lucene searches, and you represent the results as a SearchResult object:

SearchResult.java

In a SearchResult, the size property is the overall number of results from the search. The items list is a single "page" of those results to present to the user, consisting of items from firstIndex to lastIndex within the overall set.

In your templates, you have to check to see if the SearchResult exists, then see if it is empty, before you can get to the part that displays the content:

The first test checks to see if searchResult is not null (null is treated as false). The second checks to see if the search result is empty.

What we'd like is for the test to look at the searchResult directly and treat an empty search result as false, and a non-empty search result as true. This is similar to what Tapestry already does for Collections.

This is just a matter of extending the TypeCoercer service:

AppModule.java (partial)

Inside this thicket of generics and brackets is the code that treats a SearchResult as a boolean: return !input.isEmpty();.

With this in place, the previous template can be simplified:

The single test now implies that searchResult is not null and not empty.