Magento – add something in the header section

If you need to add something in the header section of all your pages, you can go on your template and add it to the files 1column.phtml, 2columns-left.phtml, 2columns-right.phtml… You can, but you shouldn’t, it’s not a good practice.

Let’s see the content of one of this file

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

You can see the section will be filled with all “head” child block, so let’s create one.

On your layout file (design/frontend/adin/default/layout/adin_page.xml), add the declaration of your new block

<layout version="0.1.0">
    <default>
        <reference name="head" before="-">
            <block type="adin_page/headerstuff" name="headerstuff" as="headerstuff" template="page/html/headerstuff.phtml" />
        </reference>
   </default>
</layout>

Create the block class in app/code/local/Adin/Page/Block/Headerstuff.php

class Adin_Page_Block_Headerstuff extends Mage_Core_Block_Template
{
    public function _construct()
    {
    }
}

And create you template file app/design/frontend/adin/default/template/page/html/headerstuff.phtml

<!-- header my stuff to put in the header -->

Magento load template from controller

To load html content of a template inside a controller, for example for ajax response, you can do :

$block = $this->getLayout()->createBlock('adin_admin/adminhtml_scheduletcrender')->setTemplate('admin/scheduletcrender.phtml');
$block->assign(array('ateliers' => $ateliers));
$html = $block->toHtml();
$response = array('html' => $html);
     
//send response as json
$this->getResponse()->setHeader('Content-type', 'application/json');
$this->getResponse()->setBody(Mage::helper('core')->jsonEncode($response));