Skip to content

Instantly share code, notes, and snippets.

@zonia3000
Last active April 14, 2016 14:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zonia3000/a4faa56ddbfbd9a20a60b2fbc3261162 to your computer and use it in GitHub Desktop.
Save zonia3000/a4faa56ddbfbd9a20a60b2fbc3261162 to your computer and use it in GitHub Desktop.
JSF h:panelGroup with custom HTML tag (very useful for ul/ol tags)

JSF h:panelGroup with custom HTML tag

JSF tag h:panelGroup can be only:

  • a span (setting its attribute layout="span") or
  • a div (setting its attribute layout="block")

There are situations in which you would being able to choose another kind of HTML tag (i.e. to avoid inserting a span/div inside an ul/ol element or to comply with some CSS constraint that result from the usage of CSS/HTML frameworks as Bootstrap).

The following composite component simulates h:panelGroup behavior adding the possibility to set a custom tag.

<?xml version="1.0" encoding="UTF-8" ?>
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:composite="http://java.sun.com/jsf/composite">

    <composite:interface componentType="customPanelGroup">
        <composite:attribute name="tag" required="true" />
    </composite:interface>

    <composite:implementation>
        <composite:insertChildren />
    </composite:implementation>
</html>
@FacesComponent("customPanelGroup")
public class CustomPanelGroup extends UINamingContainer {

    private String tagName;

    @Override
    public void encodeBegin(FacesContext context) throws IOException {

        tagName = (String) getAttributes().get("tag");

        // css "class" attribute
        String styleClass = (String) getAttributes().get("styleClass");

        ResponseWriter writer = context.getResponseWriter();
        writer.startElement(tagName, null);
        writer.writeAttribute("id", getClientId(), null);
        if (styleClass != null) {
            writer.writeAttribute("class", styleClass, null);
        }
    }

    @Override
    public void encodeEnd(FacesContext context) throws IOException {
        ResponseWriter writer = context.getResponseWriter();
        writer.endElement(tagName);
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment