Injecting Variables into a Magento CMS static block

In this tutorial i’ll show you how to inject any custom variable you need into a cms static block in place of a {{var variable_name}} tag. You’ve seen this in the email templates if you were working on them (in the matter of fact the model (filter) we’re calling is extending the same filter the email templates are using for injecting the variables).

First, let’s assume a few things:
1) the package is named ‘Company’ and the module is named ‘Module’
2) you know how to make a php module and a new block class. The block’s alias is in this example ‘module/dynamic’
3) the phtml template for the dynamic block will be dynamic.phtml
4) the block id of the static cms block will be ‘static_block’ (and you already created it in the admin)
5) you need to add the email of the current customer to the static block. The logic of when you want to show the block and everything deeper is out of the scope of this document.

First let’s look @ the phtml file, which only uses the method which we’ll create afterwards in the block class:

<?php if(Mage::getSingleton('customer/session')->getCustomer()->getId()) : ?>
<?php echo $this->getStaticBlock();?>
<?php endif;?>

As you see, we’re only checking if the customer is set and are getting the static block. So next let’s see the logic in the dynamic block class:

<?php
/**
* Just another block class
*/
class Company_Module_Block_Dynamic extends Mage_Core_Block_Template
{
/**
* This getter will return the html of your static block
* @return string
*/
public function getStaticBlock()
{
// loading the static block
$block = Mage::getModel('cms/block')
->setStoreId(Mage::app()->getStore()->getId())
->load('static_block');
/* @var $block Mage_Cms_Model_Block */
 
// setting the assoc. array we send to the filter.
$array = array();
// the array keys are named after the tags in the static block. let's say $array['customer_email'] is {{var customer_email}} in the static block. you can set as many variables you need.
$array['customer_email'] = Mage::getSingleton('customer/session')->getCustomer()->getEmail();
 
// loading the filter which will get the array we created and parse the block content
$filter = Mage::getModel('cms/template_filter');
/* @var $filter Mage_Cms_Model_Template_Filter */
$filter->setVariables($array);
 
// return the filtered block content.
return $filter->filter($block->getContent());
 
}
}
?>

Ok. Now enter somewhere in your static_block CMS block the tag {{var customer_email}} (or some other key you added) and it’ll be dynamically added into CMS block.