テンプレートの入れ子

前回に引き続き、テンプレート機能です。
今回はテンプレートの入れ子について書きます。

【前提条件】

[環境]

【内容】

まずはベースとなるテンプレートです。
「layout.xhtml」としてコンテキストルートに作成します。

<?xml version="1.0" encoding="windows-31j" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:f="http://java.sun.com/jsf/core"
      xmlns:ui="http://java.sun.com/jsf/facelets"> 
    <h:head>
        <title>テンプレート</title>
    </h:head> 
    <h:body>
        <f:view>
            <div id="header" style="background-color : #FFDDDD">
                <ui:insert name="header">
                    <ui:include src="/header.xhtml" />
                </ui:insert>
            </div>
            <div id="content" style="background-color : #DDFFDD">
                <ui:insert name="content"/>
            </div>
            <div id="footer" style="background-color : #DDDDFF">
                <ui:insert name="footer">
                    <ui:include src="/footer.xhtml" />
                </ui:insert>
            </div>
        </f:view>
    </h:body>
</html>

前回と変わりません。
「header.xhtml」と「footer.xhtml」も変わりません。

[header.xhtml]

<?xml version="1.0" encoding="Windows-31J" ?>
<ui:composition xmlns="http://www.w3.org/1999/xhtml"
    xmlns:ui="http://java.sun.com/jsf/facelets">
    共通のヘッダーです
</ui:composition>

[footer.xhtml]

<?xml version="1.0" encoding="Windows-31J" ?>
<ui:composition xmlns="http://www.w3.org/1999/xhtml"
    xmlns:ui="http://java.sun.com/jsf/facelets">
    共通のフッターです
</ui:composition>

つづいて入れ子にするテンプレートです。
「subLayout.xhtml」として作成します。

<?xml version="1.0" encoding="windows-31j" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<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"
    template="/layout.xhtml">
    <ui:define name="content">
        <div>
            サブのコンテンツ1
        </div>
        <div>
            <ui:insert name="subContent">
            </ui:insert>
        </div>
        <div>
            サブのコンテンツ3
        </div>
    </ui:define>
</ui:composition>

タグのtemplate属性には「layout.xhtml」を指定します。

インクルードする箇所はタグを使います。
これは入れ子にしない場合と同じです。

最後にインクルードする側のページです。
「subContent.xhtml」として作成します。

<?xml version="1.0" encoding="Windows-31J" ?>
<ui:composition xmlns="http://www.w3.org/1999/xhtml"
    xmlns:ui="http://java.sun.com/jsf/facelets"
    template="/subLayout.xhtml">
    <ui:define name="subContent">
        サブのコンテンツ2
    </ui:define>
</ui:composition>

「subContent.xhtml」にアクセスしてみます。

「layout.xhtml」「subLayout.xhtml」で指定した
全てのページがインクルードされています。


今回、前回とJSFインクルード機能についてかいてみましたが、
特別な設定が不要なのでかなり楽になっています。