Question

I have a cms block that is added to a page via layout xml.

<block type="cms/block" name="my_cms_block" as="my_cms_block">
    <action method="setBlockId">
        <block_id>my_cms_block</block_id>
    </action>
</block>

It is then used on a page with the following snippet.

<?php echo $this->getChildHtml('my_cms_block'); ?>

Now what I would like to do is be able to pass variables into this block from the page that can be used in the cms block itself via {{var something}}

For example we have a cms block that we want to use across a selection of product pages but in this block we want to be able to use a product attribute say name or anything really.

Was it helpful?

Solution

I don't have a solution for passing variables to the block, but I have an other solution involving custom {{...}} directives.

Here is a way to achieve what you need in your real scenario.

You need to put this in the block content

{{attribute attribute="name"}}

change name to what ever attribute code you need.

Now you need to create the attribute directive. You can basically use anything as the directive name, but make sure it is one work without any uppercase letters. So {{attr}} is ok {{productAttr}} does not work.

The cms blocks are parsed using the Mage_Widget_Model_Template_Filter, so you need to rewrite that class and add a new method:

public function attributeDirective($construction) //handles {{attribute ....}}
{
    if (!isset($construction[2])) { //if no parameters are passed ({{attribute}}) do nothing
        return '';
    }
    if (!Mage::registry('current_product')) { //if not on product context
        return '';
    }
    $params = $this->_getIncludeParameters($construction[2]);
    if (!isset($params['attribute'])) { //if no attribute code is passed
        return '';
    }
    $attributeCode = $params['attribute']; //get the attribute code
    $product = Mage::registry('current_product'); //get the current product
    $value = $product->getData($attributeCode); //get the value of the attribute
    /** @var Mage_Catalog_Helper_Output $helper */
    $helper = Mage::helper('catalog/output'); //get the output helper. The attribute might allow HTML so that needs to be parsed also.
    return $helper->productAttribute($product, $value, $attributeCode); //return the processed attribute value
}
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top