【发布时间】:2013-04-01 17:22:44
【问题描述】:
我想在 Magento 中以编程方式设置块的位置。
例如我希望我可以将一个块的位置设置为:
产品查看页面的“内容”下方
在侧边栏(左/右)
在任何其他块之前/之后。
请提出方法。
【问题讨论】:
-
你试过什么? ESL 可能是一个因素,但这些似乎是面试问题。
标签: php magento magento-layout-xml
我想在 Magento 中以编程方式设置块的位置。
例如我希望我可以将一个块的位置设置为:
产品查看页面的“内容”下方
在侧边栏(左/右)
在任何其他块之前/之后。
请提出方法。
【问题讨论】:
标签: php magento magento-layout-xml
我已经找到了解决方案。您可以使用观察者动态设置块位置。
首先在<Namespace>/<Module>/Model 目录中创建Observer.php。在此文件中写入以下代码:
class <Namespace>_<Module>_Model_Observer
{
public function set_block($observer)
{
$action = $observer->getEvent()->getAction();
$fullActionName = $action->getFullActionName();
$position = 'right';
$sub_position = 'before="cart_sidebar"';
$myXml = '<reference name="'.$position.'">';
$myXml .= '<block type="obc/obc" name="obc" template="obc/obc.phtml" '.$sub_position.' />';
$myXml .= '</reference>';
$layout = $observer->getEvent()->getLayout();
if ($fullActionName=='catalog_product_view') { //set any action name here
$layout->getUpdate()->addUpdate($myXml);
$layout->generateXml();
}
}
}
现在在config.xml 中编写以下代码来调用观察者:
<events>
<controller_action_layout_generate_blocks_before>
<observers>
<module_block_observer>
<type>singleton</type>
<class><Namespace>_<Module>_Model_Observer</class>
<method>set_block</method>
</module_block_observer>
</observers>
</controller_action_layout_generate_blocks_before>
</events>
现在您可以使用观察者在页面上的任何位置设置块的位置。
【讨论】: