Search code examples
jsffacelets

Conditionally add HTML element attribute in Facelets


Using Facelets and writing some XHTML, I cannot figure out how to create an element and then add attributes later, like in xslt if you wanted to conditionally add an attribute:

<xsl:element name="div">
    <xsl:attribute name="style">color:blue;</xsl:attribute>
</xsl:element>

Google gave some examples with JSP taglib similar to

<jsp:element name="div">
     <jsp:attribute name=".">...</jsp:attribute>
</jsp:element>

That library is not provided as standard in Facelets and searching the docs of the ones that are included doesn't show anything obvious.


Solution

  • Use <c:if><f:attribute> on a real JSF component.

    <h:panelGroup layout="block">
        <c:if test="#{bean.condition}"><f:attribute name="style" value="color:blue;"/></c:if>
    </h:panelGroup>
    

    By the way, you should really be using fullworthy CSS classes in CSS stylesheet files instead of tight-coupling style attributes over all place in markup.

    You could conditionally declare style classes as below:

    <h:panelGroup layout="block" styleClass="#{bean.condition ? 'foo' : 'bar'}" />