2011-05-09 57 views
3

我寫了一個擴展爲UIComponentBase的自定義標籤。
它在encodeBegin方法中添加了多個子組件(UIComponent)。h:panelGrid中的多個子組件的自定義Facelets-Tag

爲了佈局的目的,我想將這個Child-Components嵌套在h:panelGrid
中,但標籤在這裏的方式。

ExampleTag.java

private ExampleTag extends UIComponentBase { 

    public void encodeBegin(FacesContext context) throws IOException { 
     getChildren().add(new HtmlLabel()); 
     getChildren().add(new HtmlOutputText(); 
    } 
} 

ExampleOutput.xhtml

<html> 
    <h:panelGrid columns="2"> 
     <foo:exampleTag /> 
     <foo:exampleTag /> 
    </h:panelGrid> 
</html> 

所生成的輸出將具有在同一小區HtmlLabelHtmlOutput組件,
但我想將它們排成一行,即兩個單元格

+0

@ user745359:**歡迎使用StackOverflow!**我建議你改變你的名字和(可選)你的照片。問候 – 2011-05-09 18:17:09

回答

3
  1. h:panelGrid只能控制自己的孩子的佈局(而不是其子女的子女)
  2. 每個<foo:exampleTag />創建一個複合控件(有自己的孩子)

如果你想添加多個控件到h:panelGrid,使用其他模板機制之一。

例如,這h:panelGrid使用ui:include

<h:panelGrid columns="2"> 
     <ui:include src="gridme.xhtml"> 
     <ui:param name="foo" value="Hello,"/> 
     <ui:param name="bar" value="World!"/> 
     </ui:include> 
     <ui:include src="gridme.xhtml"> 
     <ui:param name="foo" value="Hello,"/> 
     <ui:param name="bar" value="Nurse!"/> 
     </ui:include> 
    </h:panelGrid> 

所包含的composition文件:

<!-- gridme.xhtml --> 
<ui:composition xmlns="http://www.w3.org/1999/xhtml" 
    xmlns:ui="http://java.sun.com/jsf/facelets" 
    xmlns:h="http://java.sun.com/jsf/html"> 
    <h:outputText value="#{foo}" /> 
    <h:outputText value="#{bar}" /> 
</ui:composition> 

視圖輸出的一個子集:

<table> 
<tbody> 
<tr> 
<td>Hello,</td> 
<td>World!</td> 
</tr> 
<tr> 
<td>Hello,</td> 
<td>Nurse!</td> 
</tr> 
</tbody> 
</table> 

小心用上面的工具由於沒有複合控件,因此不能在gridme.xhtml中的任何內容上明確設置ID,因此無法確保兒童名稱空間是唯一的。


組件不是標籤。

public void encodeBegin(FacesContext context) throws IOException { 
    getChildren().add(new HtmlLabel()); 
    getChildren().add(new HtmlOutputText(); 
} 

這是不建立一個複合控制一種可接受的方式。如果您這樣做,每次渲染時都會將新控件添加到組件。你也不應該在構造函數中這樣做;這也會導致問題。在控件中添加子控件沒有好方法;它應該由視圖(見上面)或a tag在外部完成。

+0

非常感謝,這是一個基本的設計錯誤。我通過檢查childCount()來「修復」在渲染階段添加組件,這也不是一個好主意! – wintersolutions 2011-05-09 17:37:12