Fragments are effectively in-line Panels, i.e. they provide a way to maintain a panel's piece of markup within the parent's markup file.

They're just there to help with the cases where you don't need to share the panel contents between different pages but are just using them on a single page. In other words, they're a convenience feature for people to embed repeating but non-reusable pieces of markup into the parent's markup file.

Example

e.g. You have a target myPanel

<span wicket:id="myPanel">Example input (will be removed)</span>

and in the same markup file you have some fragments, i.e.

<wicket:fragment wicket:id="frag1">panel 1</wicket:fragment>
<wicket:fragment wicket:id="frag2">panel 2</wicket:fragment>

Then at run-time, in your page code, you can decide which to use, e.g.

add(new Fragment("myPanel", "frag1");

which will result in the markup from frag 1 being rendered, i.e. panel 1

Advanced Example

In the code below a table is rendered where even and uneven rows have a different color.:

<html>
<head><title>Fragments Test</title></head>
<body>

<table border="1"> 
  <tr>
    <th>id</th>
    <th>Column</th>
  </tr>
  
  <span wicket:id="list">
  
   <span wicket:id="placeholderForFragmentedListItem">[content will go here]</span>
   
	<wicket:fragment wicket:id="variant_even">
	  <tr bgcolor="lightgrey">
		<td wicket:id="rownum">1</td>
		<td >Variant 1</td>
	  </tr>
	</wicket:fragment>
	
	<wicket:fragment wicket:id="variant_uneven">
	  <tr bgcolor="white">
		<td wicket:id="rownum">2</td>
		<td >Variant 2</td>
	  </tr>
	</wicket:fragment>
	
  </span>
</table>

</body>
</html>

and the corosponding Java code:

public class FragmentsTest extends WebPage {

  public FragmentsTest() {
    Loop loop = new Loop("list", 5) {
      protected void populateItem(LoopItem item) {

        String fragmentId;
        if (0 == item.getIteration() % 2) {
          fragmentId = "variant_even";
        } else {
          fragmentId = "variant_uneven";
        }

        Fragment frag = new Fragment(
				"placeholderForFragmentedListItem", fragmentId, this);
        frag.add(new Label("rownum", "" + item.getIteration()));
        item.add(frag);
      }
    };
    add(loop);
  }
}

Note

If the component that you are putting the fragment in is a subclass, the fragment's markup must be inside the <wicket:extend></wicket:extend> tag:

<wicket:extend>
    ...
    <span wicket:id="myPanel">Example input (will be removed)</span>
    ...
    <wicket:fragment wicket:id="frag1">panel 1</wicket:fragment>
    <wicket:fragment wicket:id="frag2">panel 2</wicket:fragment>
</wicket:extend>
  • No labels