5

There are two ways by which we can call a static block in a Magento phtml file;

Method-1

<reference name="footer">   
    <block type="cms/block" name="my_identifier">
        <action method="setBlockId"><block_id>my_identifier</block_id></action>  
    </block> 
</reference>

Then in the phtml file:

<?php echo $this->getChildHtml('my_identifier') ?>

Method-2

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

Which approach is better and why?

4

There at least 10 more ways we can do it ;)

In my opinion, the best way is method 1:

  • Templates should, ideally, only contain HTML and echoing of variables, child blocks, or contain very simple display logic
  • You're separating "what" (which CMS block) and "how" (HTML) which makes for easier maintenance
  • Future developers can find more easily what they're looking for. The structure of the page should be defined in layout XML. If I were to change the identifier of the CMS block, layout XML would be the first place I'd look - and many other developers as well.
2
  • What do you mean by 10 other ways. Can you give some examples?
    – Brats
    Sep 10 '15 at 10:44
  • In Magento there are many ways to do things, but method 1 is the best, so you don't have to worry about the other ones. It was mostly a joke anyways, but you can, for example, put the create block logic in your own block class (if you have one), or you could call the <action> in custom layout XML through the admin interface, or you can use the registry, or you can use a widget, or widget instance, or you can... etc. etc.
    – Erfan
    Sep 10 '15 at 13:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.