How to create a Link that supplies its own Markup?

Posted by Aranian on Stack Overflow See other posts from Stack Overflow or by Aranian
Published on 2012-10-31T22:57:48Z Indexed on 2012/10/31 23:00 UTC
Read the original article Hit count: 138

Filed under:
|

I'm trying to create a link that will hide or show a part of my page. The link should be reusable and display one of two images, depending on state.

Adding the two subcomponents on every page where I use the link is kind of clunky so I wanted to create a component that behaves like a link while automatically adding its content.

This is the Link component:

public class ToggleVisibilityLink extends AjaxFallbackLink<Boolean>
{
  public ToggleVisibilityLink(final String id, final IModel<Boolean> model)
  {
    super(id, model);

    setOutputMarkupId(true);

    add(new Image("collapseImage")
    {
      @Override
      public boolean isVisible()
      {
        return !getModelObject();
      }
    });
    add(new Image("expandImage")
    {
      @Override
      public boolean isVisible()
      {
        return getModelObject();
      }
    });
  }

  @Override
  public void onClick(final AjaxRequestTarget target)
  {
    setModelObject(!getModelObject());
    if (target != null)
    {
      target.add(this);
      send(this.getParent(), Broadcast.EXACT, target);
    }
  }
}

And this is how I currently use it in HTML (this is added to the page or panel where I use the link):

<a href="#" wicket:id="collapseExpandLink" class="collapseExpandLink">
  <wicket:link>
    <img src="collapse.png" wicket:id="collapseImage" class="collapseExpandImage collapse">
  </wicket:link>
  <wicket:link>
    <img src="expand.png" wicket:id="expandImage" class="collapseExpandImage expand">
  </wicket:link>
</a>

And the corresponding Java call:

add(new ToggleVisibilityLink("collapseExpandLink", new PropertyModel(this, "hidden")));

But I want to be able to skip the body inside the link as one would have to know about the internals of ToggleVisibilityLink. I experimented with IMarkupResourceStreamProvider, using Dynamic markup in Wicket as a starting point. By googling I found another example where the poster was only able to get that to work when using a Panel, and I was able to do that as well. But I'd really like to keep the link and not package it inside a Panel, as I would not be able to style the link in the markup.

I'm also open to alternatives to encapsulate the link and its body.

© Stack Overflow or respective owner

Related posts about java

Related posts about wicket