如何在 panelGrid 中插入条件行,同时保持行简洁?

sch*_*obe 2 jsf

我有h:panelGrid两列和多行:

<h:panelGrid columns="2">
    <p:outputLabel for="attr1" value="#{messages.attr1}" />
    <p:inputText id="attr1" value="#{viewBean.attr1}" />
    <p:outputLabel for="attr2" value="#{messages.attr2}" />
    <p:inputText id="attr2" value="#{viewBean.attr2}">
    <p:outputLabel for="attr3" value="#{messages.attr3}" />
    <p:inputText id="attr3" value="#{viewBean.attr3}" />
</h:panelGrid>
Run Code Online (Sandbox Code Playgroud)

现在,某些行只能有条件地出现。在示例中,这可能是 attr2 和 attr3。当我围绕它们构建一个<ui:fragment />条件渲染时(见下文),但是 jsf 尝试将整个块放入一个<td />表格单元格元素中。

<h:panelGrid columns="2">
    <p:outputLabel for="attr1" value="#{messages.attr1}" />
    <p:inputText id="attr1" value="#{viewBean.attr1}" />
    <ui:fragment rendered="#{viewBean.myCondition}">
        <p:outputLabel for="attr2" value="#{messages.attr2}" />
        <p:inputText id="attr2" value="#{viewBean.attr2}">
        <p:outputLabel for="attr3" value="#{messages.attr3}" />
        <p:inputText id="attr3" value="#{viewBean.attr3}" />
    </ui:fragment>
</h:panelGrid>
Run Code Online (Sandbox Code Playgroud)

另一种选择是创建两个 panelGrid。一个用于第一个块,一个用于第二个块:

<h:panelGrid columns="2">
    <p:outputLabel for="attr1" value="#{messages.attr1}" />
    <p:inputText id="attr1" value="#{viewBean.attr1}" />
</h:panelGrid>
<h:panelGrid columns="2">
    <ui:fragment rendered="#{viewBean.myCondition}">
        <p:outputLabel for="attr2" value="#{messages.attr2}" />
        <p:inputText id="attr2" value="#{viewBean.attr2}">
        <p:outputLabel for="attr3" value="#{messages.attr3}" />
        <p:inputText id="attr3" value="#{viewBean.attr3}" />
    </ui:fragment>
</h:panelGrid>
Run Code Online (Sandbox Code Playgroud)

这里的问题是,两个网格中的列现在不再简洁。有什么办法可以解决这个问题?

请注意,我有不止三行,因此rendered为每个outputLabelinputText元素添加属性将非常乏味。

Bal*_*usC 5

渲染<h:panelGrid>器仅将直接 UIComponent子级视为表格单元格,而不是更深层次的嵌套单元格。<ui:fragment>实际上也是一个UIComponent. 因此,它成为一个包含所有嵌套子项的单个表格单元格。

根据病情的来源,您有 2 个选择rendered

  1. 如果它在视图构建期间可用,请<c:if>改为使用。

    <h:panelGrid columns="2">
        <p:outputLabel ... />
        <p:inputText ... />
        <c:if test="#{viewBean.myCondition}">
            <p:outputLabel ... />
            <p:inputText ... />
            <p:outputLabel ... />
            <p:inputText ... />
        </c:if>
    </h:panelGrid>
    
    Run Code Online (Sandbox Code Playgroud)
  2. 否则,如果不能保证它在视图构建期间可用,请删除<ui:fragment>rendered在子级上重复该条件。

    <h:panelGrid columns="2">
        <p:outputLabel ... />
        <p:inputText ... />
        <p:outputLabel ... rendered="#{viewBean.myCondition}" />
        <p:inputText ... rendered="#{viewBean.myCondition}" />
        <p:outputLabel ... rendered="#{viewBean.myCondition}" />
        <p:inputText ... rendered="#{viewBean.myCondition}" />
    </h:panelGrid>
    
    Run Code Online (Sandbox Code Playgroud)

也可以看看: