Often I create little modules of content as CMS static blocks in Magento. You can easily display CMS Blocks throughout different locations on your site using Magento’s XML layout engine. However, a change in location may mean a change in context. The same CMS block may need to command more attention on one page than another. This can easily be accomplished by writing CSS based on the Magento-generated class attached to the <body> element… but that is the wrong approach.

As a frontend developer, you want to write your CSS in terms of systems not pages. You want your code to be flexible not rigid — “agile” as the backend nerds would say. Magento’s layout engine allows you to accomplish this.

Below is an example of the approach implemented in Magneto’s RWD theme. In the XML layout code, I create a generic wrapper block on which I apply the my-container class. Within that block, I call a CMS static block I created which contains the logo of my favorite super hero (at the moment). The resulting output is my CMS block wrapped in <div class="my-container">. And with that, the context of my CMS block can be changed not based on the page, but on the system.

<reference name="product.info.options.wrapper">
    <block type="page/html_wrapper" name="my_container" as="my_container">
        <action method="setElementClass"><value>my-container</value></action>
        <block type="cms/block" name="batman_logo">
            <action method="setBlockId"><block_id>batman_logo</block_id></action>
        </block>
    </block>
</reference>
Screenshot of a CMS static block being displayed on the product page of a Magento store.
Magento CMS Static Block Wrapper
Posted by: John Dugan

Comments