我想通过AJAX创建一个页面的一部分。我想到使用一个URL参数bare
,它会告诉Magento呈现一个页面,其中不同的模板应用于 root 块。 裸模板如下所示:
<?php echo $this->getChildHtml('content'); ?>
那就是它!我们的想法是,JavaScript方法只能抓取另一个页面的content
,并在适当的位置将其插入到DOM中。 (我不希望任何页面都可以实现这一点 - 只有在布局xml中标记过的页面。)
我在其他地方读过I should avoid conditional layout xml。我能想到的唯一另一种方法是覆盖Page / Html块本身,创建一个修改过的setTemplate
方法,如下所示。本能地,我担心压倒Magento这样一个核心部分。
public function setTemplate($template, $bareTemplate='')
{
$bareMode = Mage::app()->getRequest()->getParam('bare');
$targetTemplate = (!empty($bareTemplate) && $bareMode === '1') ? $bareTemplate : $template;
return parent::setTemplate($targetTemplate);
}
我想到了什么更好的方法?
答案 0 :(得分:2)
获得所需内容的关键是将 root 删除为输出块,将其替换为内容。输出块只是renderLayout();
的入口点要在Magento中执行此操作而不使用include-path-hacking Mage_Core_Controller_Varien_Action
,请观察在基本操作控制器类(ref controller_action_layout_render_before_$this->getFullActionName()
方法)中触发的Mage_Core_Controller_Varien_Action::renderLayout()
范围事件。
首先配置模型类组和前端事件观察器。您需要确定需要此逻辑的任何路由的完整操作名称。见Mage_Core_Controller_Varien_Action::renderLayout()
。示例配置如下。
<?xml version="1.0"?>
<config>
<global>
<models>
<your_classgroup>
<class>Your_Classgroup_Model</class>
</your_classgroup>
</models>
</global>
<frontend>
<events>
<controller_action_layout_render_before_FULL_ACTION_NAME...>
<observers>
<your_observer_config>
<type>model</type>
<class>your_classgroup/observer</class>
<method>makeContentBlockTheOutputBlock</method>
</your_observer_config>
</observers>
</controller_action_layout_render_before_FULL_ACTION_NAME...>
</events>
</frontend>
</config>
事件观察者逻辑很简单。这样做:
public function makeContentBlockTheOutputBlock($observer)
{
//Edit: action not passed in to this event; passed in generic generate_blocks event
if( Mage::app()->getRequest()->getParam('bare') )
{
Mage::app()->getLayout()->removeOutputBlock('root')->addOutputBlock('content');
}
}
HTH。