Understanding Templates

Layouts only define different blocks and form a nested structure of blocks, it does not tell where exactly the blocks must be presented in the page. For example the page.xml layout file only defines different structural blocks such as ‘left’,content’,right’,’head’ etc.. but it does not tell where to place them.

Visual presentation of blocks is handled by template files. They are nothing more than html files with nested php tags (phtml). The basic templates for all the pages are stored within: magento/app/design/frontend/default/default/template/page

Different parts of the system use different layouts, the home page generally uses the two column layout, while the product display uses a three column layout. The default template file for page (‘root’) is set as 3column.phtml.

3columns

Analyzing the code:

Lets take a look at this file. The first few lines are as follows:

<head>
<?php echo $this->getChildHtml(‘head’) ?>
</head>

It places the ‘head’ block on the top of the page. Templates refer to blocks by using the getChildHtml(‘blockname’) method.

Go through the rest of the code and you will find out that it is creating a 3 column layout for the page with a header and a footer division. Also it is placing blocks in the required divisions of the page. (‘header’ block is placed in header division, ’right’ block is placed in col-right side-col division…). The division <div> classes are defined in CSS files.

What is $this ?

At this point you may be confused when you see $this->. You may know that $this is used to refer to the calling object. In this case the object is an instance of Mage_Page_Block_Html (which is Mage/Page/Block/Html.php). Checkout this file and you will see the different functions you can use. Also this class extends Mage_Core_Block_Template Class. But then where is the getChildHtml() function ?. The Mage_Core_Block_Template Class extends Mage_Core_Block_Abstract. This is one of the main classes and most of the block classes is an extension of this class. In this class you can find the getChildHtml() method.

getChildHtml() method:

The getChildHtml() function is the most important function used in our template. It calls particular block defined in XML file and renders it as HTML , then outputs it to the browser. We can call blocks from everywhere and from corresponding XML files.

Understanding templates requires basic knowledge about XHTML, CSS and PHP. However most of the work of templates is done by using functions provided by Block objects. So we need to learn about Block classes to work with templates.

Leave a comment