I know that in Magento there are two ways to call a layout:
-
in controller something like:
public function indexAction(){ $this->loadLayout(); //... $block = $this->getLayout()->createBlock('core/template')->setTemplate('custom/myfile.phtml')->toHtml(); echo $block; //... $this->renderLayout(); }
-
in xml:
config.xml
<frontend> <layout> <updates> <mymodule> <file>mymodule.xml</file> </mymodule> </updates> </layout> </frontend>
mymodule.xml
<router_index_index translate="label"> ... <reference name="content"> <block type="core/template" name="block.name" template="custom/myfile.phtml"/> </reference> </router_index_index>
The both work of course but what is the best ways to do it and what is the difference between theme.
Best Answer
You are listing 2 ways to do layout updates. Let me start by giving the ways to update the layout in Magento 1 that I know. I think there are at least 6 ways to update layout XML:
local.xml
file in a themeMost of the times you will be (should be) doing the first 3. I think you should configure the layout in XML files and if it needs to be manipulated depending on user input, you could do so in a controller.
I think you could also do stuff with layout in a Block class, there are some cases where this can be considered. I'd never manipulate layout in a PHTML file. If you end up doing that, move it to the Block class code.
Of course, a special case, you can set layout updates on CMS pages. I'd also advise you to only do this in special cases.
The reason one thing is considered good practice and the other not very good practice is traceability: The first place you will look to understand why something is happening is in the layout XML files. The last place you would think of to look is those CMS layout updates.
Now, the difference between layout updates through a module (XML file configured in
config.xml
) and in a theme (theme'slocal.xml
) can sometimes be a bit of a gray area. I would state that:Module layout updates can be providing layout for layout handles specific for your module's controllers. Theming updates should therefore typically affect handles and blocks that are present in the Magento core.