We all know about templates in webpages. How we can add our content in those templates and use them according to our needs. This gives a general control over the content so that we can avoid errors and make them more alike. Likewise even Visualforce gives us the power to write custom templates so that we can use them according to our needs. And today I am going to tell you how to write a template in visualforce.
Visualforce Page Code
For this example I’ll create a Visualforce page named templatepage, which will be out template Visualforce page. Here is the code for template page:
<apex:page>
<apex:insert name="head"/><br/>
<apex:outputText>This is the default text that will appear in every page.</apex:outputText>
<apex:insert name="body"/>
</apex:page>
In the above code we can see that this page is like any normal Visualforce page except that there is a tag which is not doing anything on it’s own. That tag is <apex:insert>, which acts as the markup for the content to be added in the template.
Next we’ll create a page which will use this page as a template. Let’s name the new Visualforce page as myPage. The code will be as follows:
<apex:page controller="mycontroller">
<apex:composition template="templatepage">
<apex:define name="head">
Account List
</apex:define><br/>
<apex:define name="body">
<apex:dataTable value="{!list}" var="l">
<apex:column value="{!l.name}" headerValue="Name"/>
<apex:column value="{!l.industry}" headerValue="Industry"/>
</apex:dataTable>
</apex:define>
</apex:composition>
</apex:page>
As we can see in this code that the template is used with the help of the <apex:composition> and the attribute template tells which page to use as the template. The <apex:define> tells where to insert the new code. It’s name attribute selects the markup, which we previously defined, to insert the code.
For this particular example I have also written an apex class which is feeding the datatable:
public class mycontroller {
/**
* Webkul Software.
*
* @category Webkul
* @author Webkul
* @copyright Copyright (c) 2010-2017 Webkul Software Private Limited (https://webkul.com)
* @license https://store.webkul.com/license.html
**/
public list<account> getlist(){
list<account> acc = [select name, industry from account limit 1000];
return acc;
}
}
Output
SUPPORT
That’s all for how to write a template in visualforce, for any further queries feel free to contact us at:
https://wedgecommerce.com/contact-us/
Or let us know your views on how to make this code better, in comments section below.