测试ui:insert是否已在模板客户端中定义

时间:2014-09-27 02:31:46

标签: templates jsf-2 facelets

我想知道是否可以知道ui:insert中是否定义了ui:composition。 我知道我可以使用单独的ui:param来完成它,但只是想这样做而不是为了保持简单并且不易出错。

示例:

模板

...
<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>
...

第1页

...
<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>
...

1 个答案:

答案 0 :(得分: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>

这样您只需要担心在客户端视图中包含侧边栏。

相关问题