2014-09-27 28 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