<apex:include> を使用する既存ページの参照
何も変更を行わずに他のページのコンテンツ全体を複製する場合は、<apex:include> タグを使用します。この技法を使用すると、複数の場所で同じように使用する既存のマークアップを参照することができます。
たとえば、ユーザーの名前を取得して表示するフォームを作成するとします。最初に、formTemplate というページを作成して、再利用可能なフォームを表し、templateExample というコントローラーを使用します。
1<apex:page controller="templateExample">
2
3</apex:page>
templateExample が存在しないというメッセージが表示されたら、次のコードを使用してカスタムコントローラーを定義します。
1public class templateExample{
2
3 String name;
4 Boolean showGreeting = false;
5
6 public PageReference save() {
7 showGreeting = true;
8 return null;
9 }
10
11 public void setNameField(String nameField) {
12 name = nameField;
13 }
14
15 public String getNameField() {
16 return name;
17 }
18
19 public Boolean getShowGreeting() {
20 return showGreeting;
21 }
22}次に、formTemplate に戻り、次のマークアップを追加します。
[保存] をクリックしても何も起こりません。これは予期される動作です。
1<apex:page controller="templateExample">
2 <apex:form>
3 <apex:outputLabel value="Enter your name: " for="nameField"/>
4 <apex:inputText id="nameField" value="{!nameField}"/>
5 <apex:commandButton action="{!save}" value="Save" id="saveButton"/>
6 </apex:form>
7</apex:page>次に、formTemplate を含む displayName というページを作成します。
1<apex:page controller="templateExample">
2 <apex:include pageName="formTemplate"/>
3 <apex:actionSupport event="onClick"
4 action="{!save}"
5 rerender="greeting"/>
6 <apex:outputText id="greeting" rendered="{!showGreeting}" value="Hello {!nameField}"/>
7</apex:page>このページを保存すると、formTemplate ページ全体がインポートされます。名前を入力し、[保存] をクリックすると、フォームから true 値が showGreeting 項目に渡されて、<apex:outputText> とユーザー名が表示されます。
別の Visualforce ページを作成し、ページで formTemplate を使用して異なる挨拶文を表示することもできます。displayBoldName というページを作成し、次のマークアップを使用します。
表示されるテキストが変更されても、templateExample ロジックは同じままです。
1<apex:page controller="templateExample">
2 <style type="text/css">
3 .boldify { font-weight: bolder; }
4 </style>
5 <apex:include pageName="formTemplate"/>
6 <apex:actionSupport event="onClick"
7 action="{!save}"
8 rerender="greeting"/>
9 <apex:outputText id="greeting" rendered="{!showGreeting}"
10 styleClass="boldify"
11 value="I hope you are well, {!nameField}."/>
12</apex:page>