Magento中每个Http请求结果中都会有一些布局句柄,这些句柄可以用来定制所需页面的布局。如果你曾经尝试找出magento中的布局句柄,你会发现有很多。这些句柄基于不同的变量,不同的计算。

根据用户是否登录,magento使用customer_logged_in和customer_logged_out句柄。不同的店铺也有不同的布局更新(例如STORE_default,STORE_cars,STORE_fashion ...)。主题有自己的布局句柄(例如THEME_frontend_default_default,THEME_frontend_enterprise_default)。

当一个网站使用“Shop by Brand”插件的时候,客户问我们是否能改变一个brand页面的布局。为了实现这个功能,我们必须扩展这个插件,让每个brand页面有它自己的更新句柄。

你可能注意到Magento使用这个功能创建唯一的布局句柄给不同的类别(如CATEGORY_96,CATEGORY_35)和产品(如PRODUCT_22735,PRODUCT_225)。

下面我将演示如何创建一个特定对象的布局句柄功能。句柄将由对象的ID(如OUR_COOL_OBJECT_535,OUR_COOL_OBJECT_863)字符串组成。

1、创建观察者

为了避免增加句柄到Magento布局更新对象过晚,我们需要观察controller_action_layout_load_before时间。


<config>
    <frontend>
        <events>
            <controller_action_layout_load_before>
                <observers>
                    <alwayly_controller_action_layout_load_before>
                        <class>alwayly_layouthandle/observer</class>
                        <method>controllerActionLayoutLoadBefore</method>
                    </alwayly_controller_action_layout_load_before>
                </observers>
            </controller_action_layout_load_before>
        </events>
    </frontend>
</config>

2、添加句柄

现在我们必须计算布局更新句柄并将它添加到布局更新对象里。


<?php
 
    class Alwayly_LayoutHandle_Model_Observer
    {
        public function controllerActionLayoutLoadBefore(Varien_Event_Observer $observer)
        {
            /** @var $layout Mage_Core_Model_Layout */
            $layout = $observer->getEvent()->getLayout();
 
            $id = Mage::app()->getRequest()->getParam('id');
 
            /* or */
 
            if($ourCoolObject = Mage::registry('our_cool_object'))
            {
                $id = $ourCoolObject->getId();
            }
 
            $layout->getUpdate()->addHandle('OUR_COOL_OBJECT_'.$id);
        }
    }

360magento提供专业的基于magento系统的跨境电商平台网站开发和托管服务,如有需求或相关咨询,请与我们联系