Magento: If/Else Condition in Layout XML to Show/Hide Block

You can put IF condition in Layout XML file of Magento to show or hide any block. The IF condition checks for the Yes/No value of configuration settings.

Suppose, you have a custom module. You have a custom block that you want to show in left and right sidebar. You have two Yes/No configuration settings to show/hide the custom block on left sidebar and right sidebar.

Then, you can first define your custom block and then use IF condition (ifconfig) in the action method append to show or hide the block in left or right sidebar. If the configuration settings for left sidebar is set as ‘Yes‘ then the block will be displayed in left sidebar. If it is set as ‘No‘ then the block will not be displayed in the left sidebar. It’s similar for right sidebar as well.

Here is the Layout XML code:


<default>
	<block type="yourmodule/yourmodule" name="yourmodule.sidebar" before="-" template="yourmodule/block_sidebar.phtml"/>
	<reference name="left">		
		<action method="append" ifconfig="yoursection/yourgroup/yourfield_to_show_hide_left_sidebar">
			<block>yourmodule.sidebar</block>
		</action>
	</reference>        
	<reference name="right">
		<action method="append" ifconfig="yoursection/yourgroup/yourfield_to_show_hide_right_sidebar">	
			<block>yourmodule.sidebar</block>
		</action>	
	</reference>
</default>

Hope this helps. Thanks.