【问题标题】:Set position of block programmatically in Magento在 Magento 中以编程方式设置块的位置
【发布时间】:2013-04-01 17:22:44
【问题描述】:

我想在 Magento 中以编程方式设置块的位置。

例如我希望我可以将一个块的位置设置为:

  1. 产品查看页面的“内容”下方

  2. 在侧边栏(左/右)

  3. 在任何其他块之前/之后。

请提出方法。

【问题讨论】:

  • 你试过什么? ESL 可能是一个因素,但这些似乎是面试问题。

标签: php magento magento-layout-xml


【解决方案1】:

我已经找到了解决方案。您可以使用观察者动态设置块位置。 首先在<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>

现在您可以使用观察者在页面上的任何位置设置块的位置。

【讨论】:

  • 为什么不能使用 insert(blockname,兄弟, after, alias) 方法?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-09-03
  • 1970-01-01
  • 1970-01-01
  • 2018-11-20
  • 1970-01-01
  • 1970-01-01
  • 2021-09-26
相关资源
最近更新 更多