Magento: Adding Blocks to Templates

Once again, whilst working on a clients website, my client requested certain additions to the website that would, in my opinion, be best added using block. Static CMS blocks and blocks to include items such as featured products can use a line of php in any of our phtml files within the template folder of our themes. Although the same result can be replicated using the XML layout files, I prefer to go about this task in this way.


How to fetch CMS Blocks using PHP

The first example I am going to explain shows how to load CMS Blocks into your template files. If you’re building a template that will be used by other people, it would be best to not use this, since adding CMS Blocks means the static cms block needs to exist in the installation of the Magento site.

echo $this->getLayout()->createBlock('cms/block')->setBlockId('contacts_text')->toHtml();

Fetching Template Blocks using PHP

The next example I will explain shows you how to add any other block type with a specified template, the example below illustrates grabbing the related products list.

This example would be perfectly acceptable to use in a template that will be redistributed.

echo $this->getLayout()->createBlock('catalog/product_list_related')->setTemplate('catalog/product/list/related.phtml')->toHtml();


If you really felt like challenging yourself, by all means attempt using the XML layout files to display the blocks, however these snippets speed up the site development with a simple line of code which is why I am recommended this option instead.

The following two tabs change content below.

Shane Richardson

Web Developer / Admin at HL Training Services
I have worked at various companies developing E-Commerce websites, and am keen to improve my developing skills. I also enjoy networking and maintenance. I graduated from University of the West of England and achieved a 2:2 in BSc Computing.

Latest posts by Shane Richardson (see all)