如果只渲染至少两个子节点(标题+项目),如何渲染JSF组件?

时间:2016-06-03 19:36:51

标签: jsf el conditional-rendering

我有一个:

<h:panelGroup />
  <h:outputText value="title" />
  <h:itemThatSometimesWillShow rended="sometimes1" />
  <h:itemThatSometimesWillShow rended="sometimes2" />
  <h:itemThatSometimesWillShow rended="sometimes3" />
  ...many more

我希望如果没有itemThatSometimesWillShow显示,整个面板(标题,实际上)也没有显示。

我确实尝试使用复合组件#{cc.childCount} > 1,但我不在复合实现中,所以看起来总会返回0

有什么想法吗? (我正在搜索js或EL的内容,以便在父panelGroup的rendered属性中使用)

2 个答案:

答案 0 :(得分:4)

这可以通过EL 3.0流API实现。我最初的尝试是:

<h:panelGroup rendered="#{component.children.stream().filter(c -> c.rendered).count() gt 1}">
    <h:outputText value="title" />
    <h:panelGroup rendered="#{false}">item1</h:panelGroup>
    <h:panelGroup rendered="#{false}">item2</h:panelGroup>
    <h:panelGroup rendered="#{false}">item3</h:panelGroup>
</h:panelGroup>

然而,这并没有很好地发挥作用。它意外地遇到了无限循环,最终以OutOfMemoryError结束。看来#{component} EL变量仍然代表咨询rendered属性时的前一个组件。这有点鸡蛋问题:仅当#{component}属性评估rendered时,才会注入当前组件的true

鉴于此,我可以看到另外两个选项:按ID显式查找组件,如下所示

<h:panelGroup id="foo" rendered="#{component.findComponent('foo').children.stream().filter(c -> c.rendered).count() gt 1}">
    <h:outputText value="title" />
    <h:panelGroup rendered="#{false}">item1</h:panelGroup>
    <h:panelGroup rendered="#{false}">item2</h:panelGroup>
    <h:panelGroup rendered="#{false}">item3</h:panelGroup>
</h:panelGroup>

或让它打印一些CSS类,而后者又会display:none;

<h:panelGroup styleClass="#{component.children.stream().filter(c -> c.rendered).count() gt 1 ? 'show' : 'hide'}">
    <h:outputText value="title" />
    <h:panelGroup rendered="#{false}">item1</h:panelGroup>
    <h:panelGroup rendered="#{false}">item2</h:panelGroup>
    <h:panelGroup rendered="#{false}">item3</h:panelGroup>
</h:panelGroup>

答案 1 :(得分:2)

我很快就会这样做:

<h:panelGroup rendered="{bean.isSometimes()}"/>
  <h:outputText value="title" />
  <h:itemThatSometimesWillShow rended="{bean.isSometimes1()}" />
  <h:itemThatSometimesWillShow rended="{bean.isSometimes2()}" />
  <h:itemThatSometimesWillShow rended="{bean.isSometimes3()}" />

并在bean中:

public boolean isSometimes()
{
    return isSometimes1() || isSometimes2() || isSometimes3();
}