Conditional Rendering

January 12, 2008

If you want to render a component in Wicket conditionally, it is not as straightforward. Wicket generates component hierarchy based on java and markup files. Therefore you can’t have a conditional if-else in java because markup(html) doesn’t support if-else. A workaround is to hide the component.We can create a component adaptor that will wrap our component that needs to be conditionally rendered. Adaptor will extend Border class.

import org.apache.wicket.Component;
import org.apache.wicket.markup.html.border.Border;

public abstract class ConditionalRenderAdaptor extends Border {
/**
* Component that provides conditional rendering to the child component
*
* @param id
* @param child
*/
public ConditionalRenderAdaptor(String id, Component child) {
super(id);
add(child);
setVisible(renderCondition());
}

public abstract boolean renderCondition ();
}

And the markup looks like this

<wicket:border>
<table width=”0%” border=”0″>
<tr>
<td width=”0%” valign=”top”>
<wicket:body/>
</td>
</tr>
</table>
</wicket:border>

Example

You want to hide an instance of class Record, if the user hasn’t registered yet and show it if the user has registered.Extend ConditionalRenderAdaptor and provide an implementation for renderCondition().

class Record extends ConditionalRenderAdaptor {

private static final long serialVersionUID = 1L;

public Record() {
super(“record”, new Label(“User Name”, new Model (user.getUserName() )) );
}

@Override
public boolean renderCondition() {
return user != null;
}

}

You can use it like this:

class HomePage extends WebPage {

….

Record userRecord= new Record ();

add(userRecord);

}

and in the markup:

<span wicket:id=”record” >

<tr>

<td>

<span wicket:id=”userName”>some value</span>

</td>

</tr>

</span>

“userName” will only show if the user record exists.This is not a perfect solution and if anyone knows how to do actual conditional rendering please let me know!

Tags:

5 Responses to “Conditional Rendering”

  1. Jonathan Locke Says:

    This is not necessary. Override isVisible.

  2. Alex Says:

    What is the advantage of this method over just overriding the isVisible method?

  3. wicketthings Says:

    Sometimes you want to use markup that has no direct associating in wicket, for example format html using layout, without actually over-riding data table.
    If that is what you do, then you have outer html attributes (i.e formating) they would still be visible if setVisible() over-riden. That is why you want to wrap them in an adaptor, in my humble opinion.

  4. Alex Says:

    Also, there is wicket:enclosure tag, which you can use to wrap the markup you want to hide/show.

  5. wicketthings Says:

    Ah. Great to know :) .
    Here is a link describing this behavior.
    http://cwiki.apache.org/WICKET/wickets-xhtml-tags.html
    Thank you all for commenting.


Leave a Reply