Injecting Variables into a Magento CMS static block

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.

You made it all the way down here so you must have enjoyed this post! You may also like:

How To Connect Google Analytics 4 To Magento 2 Bojan Mareljic
Bojan Mareljic, | 36

How To Connect Google Analytics 4 To Magento 2

How to keep your CMS blocks organized (and not go insane) Adrian Bece
Adrian Bece, | 11

How to keep your CMS blocks organized (and not go insane)

Simple random banner rotator in Magento using static blocks Tomas Novoselic
, | 42

Simple random banner rotator in Magento using static blocks

9 comments

  1. To inject varaibales in CMS Page:

    class Company_Module_Block_Page extends Mage_Cms_Block_Page
    {
    protected function _toHtml()
    {
    /* @var $helper Mage_Cms_Helper_Data */
    $helper = Mage::helper(‘cms’);
    $processor = $helper- >getPageTemplateProcessor();
    $aCustomVar = array();
    $aCustomVar[‘customer_email’] = Mage::getSingleton(‘customer/session’)->getCustomer()->getEmail();
    $processor->setVariables($aCustomVar);
    $html = $processor->filter($this->getPage()->getContent());
    $html = $this->getMessagesBlock()->toHtml() . $html;
    return $html;
    }
    }

    To use the variable in the CMS Page you can use the below code:
    {{if customer_email}} {{var customer_email}} {{/if}}

    Cheers,
    Swapna

  2. Good post, i am trying to get this working in a cms block on product page that show the product_name dinamically but i have no success now. I have created the module with some variations in the php and phtml files;

    In the php i have included:


    $array['product_name'] = Mage::getModel('catalog/product')->getCollection()->getName();

    And in the phtml:


    getCollection()->getName()) : ?>
    getStaticBlock();?>

    Also i have declared de block class in xml file. Any advice on what is wrong will be appreciated, thanks.

  3. SORRY for my first post …

    I often encounter this problem .. can you help me please.

    ->Since I am a beginner in Magento i used to add/delete some codes and checked if what will happened in the front end. I once add a code in \app\design\frontend\default\corregidor-new\template\catalog\navigation\top.phtml

    the existing code there is :

    <?php $_menu = $this->renderCategoriesMenuHtml(0,'level-top') ?>
    <?php if($_menu): ?>
    <div class="nav-container">
        <ul id="nav">
            <?php echo $_menu ?>
        </ul>
    </div>
    <?php endif ?>

    –> my frontend displays the list of saved categories in the navigation bar. Then I change the code to this:

    <div class="nav-container">
        <ul id="nav">
    
    	<?php echo $this->getLayout()->createBlock('cms/block')->setBlockId('menu')->toHtml();?>
    	</ul>		
    </div>

    –> in the frontEnd the tab in the navigation bar change which is correct as i expected. Then when I tried to edit it again… There is no changes happened even I refreshed it again and again… I even tried to return the old code but nothing happens.. What do you think are the possible problems why nothing happens?

    β€”>Thank you so much πŸ™‚

  4. Nope, it woudn’t.

    But, I’ve looked a little bit through the core code and found out that the widget module has it’s own filter (which is in the matter of fact just extending the cms/template_filter with a additional widget directive).

    So, if you need to parse a widget in your static block, you can use the filter model ‘widget/template_filter’ instead of the ‘cms/template_filter’ and it should work (I tried it out, it worked for me).

    P.S. sorry for the late response.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <blockquote cite=""> <code> <del datetime=""> <em> <s> <strike> <strong>. You may use following syntax for source code: <pre><code>$current = "Inchoo";</code></pre>.

Tell us about your project

Drop us a line. We'd love to know more about your project.