How not to set an attribute of a component inside

2019-05-23 08:30发布

问题:

I have a h:graphicImage in a composite component like this:

<composite:interface>
    <composite:attribute name="name" required="true" type="java.lang.String" />
    <composite:attribute name="alt" required="false" type="java.lang.String" />
    <composite:attribute name="height" required="false" type="java.lang.String" />
    <composite:attribute name="width" required="false" type="java.lang.String" />
</composite:interface>

<composite:implementation>

    <h:graphicImage url="something-common#{cc.attrs.name}"
                alt="#{cc.attrs.alt}"
                height="#{cc.attrs.height}"
                width="#{cc.attrs.width}" />

</composite:implementation>

This works, however, if some attributes are not set (e.g. width, height) they are rendered empty. In IE9 on win7 this causes the img tag width and height attribute to be rendered as 1. So the images have 1px width and 1px height.

回答1:

You can conditionally add attributes via <c:if><f:attribute>.

<h:graphicImage ...>
    <c:if test="#{not empty cc.attrs.height}"><f:attribute name="height" value="#{cc.attrs.height}" /></c:if>
    <c:if test="#{not empty cc.attrs.width}"><f:attribute name="width" value="#{cc.attrs.width}" /></c:if>
</h:graphicImage>

See also:

  • JSTL in JSF2 Facelets... makes sense?