:::: MENU ::::

Magento Certification: Rendering Blocks (part 2)

4.00 avg. rating (75% score) - 2 votes

Describe the relationship between templates and blocks

Can any block in Magento use a template file?

The template file usage in Magento is restricted to Mage_Core_Block_Template and blocks inheriting from it.

Other blocks in Magento like Mage_Core_Block_Text does not inherit from it but from Mage_Core_Block_Abstract so it cannot use a template file for rendering.

How does the $this variable work inside the template file?

In Magento, the template file for each block is ‘included’ by a php include directive during the render phase, so it´s clear that $this inside a template file, always refer to the block class instance.

The include is done in the fetchView() method of Mage_Core_Block_Template.

Is it possible to render a template without a block in Magento?

Well, never knows what’s the correct answer to some like this. This is not possible in a non-tricky way, but you may copy part of the fetchView() to make it works… Definitely not a good practise, but possible any way.

The include of a template in a Magento Block is as follows:

public function fetchView($fileName)
{
    . . .

    // Templates can be output directly to the browser or its content added to
    // the response which at the end of the process is sent to the browser
    // in one piece. In most cases, it will be stored in the response and
    // Magento will send it at the end of the request processing
    $do = $this->getDirectOutput();
    if (!$do) {
        ob_start();
    }

    . . .

    // This part includes the template file directly, so it's result is output 
    // directly or captured to a variable (see ob_start and ob_get_clean calls)
    // The template file path is generated by realpath...
    $includeFilePath = realpath($this->_viewDir . DS . $fileName);
    if (strpos($includeFilePath, realpath($this->_viewDir)) === 0 || $this->_getAllowSymlinks()) {
        include $includeFilePath;
    } else {
        Mage::log('Not valid template file:'.$fileName, Zend_Log::CRIT, null, null, true);
    }
     
    . . .

    // Finally the generated output by the template, is captured or output.
    if (!$do) {
        $html = ob_get_clean();
    } else {
        $html = '';
    }
    . . .
}

Is it possible to have a block without a template in Magento?

Of course yes… in fact, the only predefined block class in Magento that uses a template file is Mage_Core_Block_Template. It is the most used, but not the only block class in Magento.

Other classes in Magento like Mage_Core_Block_Text or Mage_Core_Block_Text_List doesn’t use a template file.




Hey! Qué opinas sobre el artículo?