有条件地渲染复合组件中元素的属性

2023-11-22

我有以下复合组件:

<?xml version="1.0" encoding="UTF-8"?>
<ui:component xmlns="http://www.w3.org/1999/xhtml"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:ui="http://java.sun.com/jsf/facelets"
    xmlns:c="http://java.sun.com/jsp/jstl/core"
    xmlns:f="http://java.sun.com/jsf/core"
    xmlns:p="http://primefaces.org/ui"
    xmlns:fn="http://java.sun.com/jsp/jstl/functions"
    xmlns:composite="http://java.sun.com/jsf/composite">

    <composite:interface>
        <composite:attribute required="true" name="field" />
        <composite:attribute required="true" name="value" />
        <composite:attribute required="false" name="size"/>
    </composite:interface>

    <composite:implementation>
    ...
            <div class="wrapper">
                <h:inputText value="#{cc.attrs.value}"
                    id="#{field.id}" 
                    rendered="#{field.rendered}" 
                    size="#{cc.attrs.size}">
                </h:inputText>
                <h:messages for="#{field.id}" styleClass="errorMessage"/>
            </div>
    ...
    </composite:implementation>
</ui:component>

问题是当我使用这个组件而不设置它的size属性,它仍然被渲染为size=0在 html 输入元素中。

我想要的是渲染嵌套h:inputText仅当它具有有效值(例如非空)时才使用它的属性。或者,如果没有显式覆盖嵌套元素的所有属性,我想公开它们。

怎么可能呢?


你可以使用JSTL<c:if>有条件地构建视图<f:attribute>单独指定一个属性:

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

另一种方法是为复合组件属性指定默认值:

<cc:attribute name="size" required="false" default="10" />
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

有条件地渲染复合组件中元素的属性 的相关文章

随机推荐