July 5, 2011

OK, this one is a bit of an edge case, but I’ve dealt with similar issues while trying to set a static block through a template file when you need that static block to change based on the product being viewed.

Sure, it’s easy to call the static block in the product’s custom layout update, but the problem there is that you can’t place that block anywhere between the title and product description. All of those elements are called as childHtml and can’t be referenced by the layout XML. What happens if you need to put a special notice near the price or short description?

You could create a custom theme for each different product, but that could lead to a maintenance nightmare when you need to update a product page. You could also create a custom block and template, but that takes a lot of effort.

We’ll start by looking at calling a static block in the template file. It’s fairly academic to add the static block in the template’s phtml code in Magento:

<?php echo $this->getLayout()->createBlock('cms/block')->setBlockId('my_static_block')->toHtml() ?>

This works great, but every product page will have the exact same static block.

In this particular case, I needed to add some pricing information based on the product’s SKU. For simplicity I’ll say the SKUs were 1, 2, and 3. In this case, I created a static block for each of the three pricing notes, and set the identifier to product1, product2, and product3 respectively.

Magento Dynamically Set Static Block From Template

Now, in the template file, I’ve changed the way the setBlockId is called:

<?php echo $this->getLayout()->createBlock('cms/block')->setBlockId('pricing'.$_product->getSku())->toHtml() ?>

This way the setBlockId would change depending on the product SKU. In theory this can also be done with custom attributes or any other product value. As an added bonus, it fails gracefully if it encounters a static block that doesn’t exist. Say for SKU = 4 I haven’t created a static block, so on that product page, no extra html is generated and no errors occur.

As I said, it’s a bit of an edge case, but it might come in handy in that rare instance.

Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Mixx
  • LinkedIn
  • Technorati
  • Slashdot
  • Yahoo! Buzz
  • Google Bookmarks
  • Ping.fm
  • Reddit
  • StumbleUpon
  • Suggest to Techmeme via Twitter
  • Twitter

Leave a Reply