Apex:Insert in Visualforce

apex:Insert is a template component that declares a named area that must be defined by an <apex:define> component in another Visualforce page. Use this component with the <apex:composition> and <apex:define> components to share data between multiple pages.

Sometimes we have a situation that we need to share the same data between multiple pages with some modifications. In order to achieve that we need to write the code at multiple places which is not a best practice and it violates the DRY(Don’t Repeat Yourself) principle. This is where apex:Insert, apex:Composition and apex:Define come into the picture.

In the example below I am using a Visualforce Page as a Template and Inserting the data dynamically into that template using another Visualforce page.

Visualforce Page:
ApexTemplateVFPage

<apex:page controller="apexInsertController">
    <h1 style="color:Red"><apex:insert name="Title" /></h1>
    <br/>
    <br/>
    <apex:form >
        <apex:pageBlock>
            <apex:outputLabel value="First Name: " for="firstNameField"/>
            <apex:inputText id="firstNameField" value="{!FirstName}"/>
            <br/>        <br/>
            
            <apex:insert name="LastNameSection" />
            <br/>        <br/>
            
            <apex:insert name="AgeSection" />
            <br/>        <br/>
            
            <apex:pageBlockButtons location="bottom">
                <apex:commandButton action="{!save}" value="Save" id="saveButton"/>
            </apex:pageBlockButtons>
        </apex:pageBlock>
    </apex:form>
</apex:page>

Apex Code:

public class apexInsertController{
    public String FirstName{get;set;}
    public String LastName{get;set;}
    public String Age{get;set;}
    public String colorField {get;set;}
    
    public apexInsertController()
    {
    }
    
    public PageReference save() {
        return null;
    }
    
}

Visualforce Page:
ApexInsertVFPage

<apex:page controller="apexInsertController">
    <apex:messages />
    
    <apex:composition template="ApexTemplateVFPage">
        <apex:define name="Title">How to write templates In Visual Force page
        </apex:define>
        
        <apex:define name="LastNameSection">
            <apex:outputLabel value="Last Name: " for="lastNameField"/>
            <apex:inputText id="lastNameField" value="{!LastName}"/>
        </apex:define>
        
        <apex:define name="AgeSection">
            <apex:outputLabel style="margin-left: 37px;" value="Age: " for="ageField"/>
            <apex:inputText id="ageField" value="{!Age}"/>
        </apex:define>
        
    </apex:composition>
    
</apex:page>