2014-09-27 54 views
8

我想知道是否有可能知道ui:insert是否在ui:composition中定義。 我知道我可以使用單獨的ui:param來做到這一點,但是爲了保持簡單並且不易出錯,只是爲了不做。測試是否已經在模板客戶端中定義了ui:insert

實施例:

模板

... 
<ui:insert name="sidebar" /> 

<!-- Conditionnaly set the class according if sidebar is present or not --> 
<div class="#{sidebar is defined ? 'with-sidebar' : 'without-sidebar'}"> 
    <ui:insert name="page-content" /> 
</div> 
... 
... 
<ui:define name="sidebar"> 
    sidebar content 
</ui:define> 

<ui:define name="page-content"> 
    page content 
</ui:define> 
... 

頁2

... 
<ui:define name="page-content"> 
    page content 
</ui:define> 
... 

回答

10

ui:param對我來說是最好的選擇。這只是以正確的方式使用它的問題。作爲一個簡單的例子,我在這裏定義一個參數來指定是否存在邊欄。請記住,您可以在模板中定義一個默認的插入定義,所以才宣佈它裏面:

的template.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"> 

    <ui:insert name="sidebar"> 
     <!-- By default, there's no sidebar, so the param will be present. 
      When you replace this section for a sidebar in the client template, 
      the param will be removed from the view --> 
     <ui:param name="noSideBar" value="true" /> 
    </ui:insert> 

    <div class="#{noSideBar ? 'style1' : 'style2'}"> 
     <ui:insert name="content" /> 
    </div> 

</ui:composition> 

然後夫婦的意見在這裏,一個使用工具條和其他與沒有側欄。您可以測試它並查看瀏覽器中樣式的變化。您會注意到,第二個#{noSideBar}沒有任何價值,在任何EL條件語句中這個值都將評估爲false

page1.xhtml

<ui:composition xmlns="http://www.w3.org/1999/xhtml" 
    xmlns:ui="http://java.sun.com/jsf/facelets" template="/template.xhtml"> 
    <ui:define name="content"> 
     No sidebar defined? #{noSideBar} 
    </ui:define> 
</ui:composition> 

page2.xhtml

<ui:composition xmlns="http://www.w3.org/1999/xhtml" 
    xmlns:ui="http://java.sun.com/jsf/facelets" template="/template.xhtml"> 
    <ui:define name="sidebar" /> 
    <ui:define name="content"> 
     No sidebar defined? #{noSideBar} 
    </ui:define> 
</ui:composition> 

這樣,你只需要擔心,包括在客戶視圖的側邊欄與否。

+0

謝謝你,我從來沒有想過那樣,我馬上就試試! – 2014-09-30 01:50:34