Wrap Magneto CMS Block in Custom Class

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>
Screenshot of a CMS static block being displayed on the product page of a Magento store.
Magento CMS Static Block Wrapper

6 thoughts on “Wrap Magneto CMS Block in Custom Class”

  1. It’s not a single file, it’s a series of XML files in: [magento_root]/app/design/frontend/[your_package]/[your_theme]/layout

    However, layout overrides can be done in a single file if you want to set things up that way. You create a file named `local.xml` and apply layout overrides there. I chose a different route for State Supply, detailed here: https://www.sonassi.com/knowledge-base/the-nolocal-theming-and-packaging-methodology/

    Based on your comment, I think a good place for you to start would be reading the Magento Design Guide: https://john-dugan.com/wp-content/uploads/2015/09/magento-design-guide.pdf

    You should fully understand how Magento works on the frontend before you dig yourself in to a hole. Hope that helps ๐Ÿ™‚

Leave a Reply

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