Magento:在每个前端页面中添加链接

时间:2017-01-22 01:15:09

标签: php magento magento-1.9

我有一个模块需要在前端的每个页面上注入Advanced Settings" - Disable Http Cache (when toolbox is open)的规范链接。有办法吗?目前,鉴于我的模块在前端不需要自己的页面,也不需要任何控制器,我只在config.xml中设置了帮助器。现在,我在布局中确实有一个xml,但问题是我需要根据用户输入(在管理员中)更改规范链接属性,因此XML不适合。是的,我确实可以打开前面的布局xml文件,然后替换我需要的内容,然后将新内容写回去,但我想首先检查是否还有其他方法可以实现。

1 个答案:

答案 0 :(得分:2)

您可以访问core_block_abstract_prepare_layout_before事件并使用Head块的addLinkRel方法添加链接标记。

在你的config.xml中,你需要定义一个像这样的观察者:

<events>
    <core_block_abstract_prepare_layout_before>
        <observers>
            <your_module>
                <class>Your_Module_Model_Observer</class>
                <method>addCanonicalLink</method>
            </your_module>
        </observers>
    </core_block_abstract_prepare_layout_before>
</events>

在Model目录中创建一个观察者类

<?php
class Your_Module_Model_Observer {
    public function addCanonicalLink(Varien_Event_Observer $observer) {
        $block = $observer->getData('block');
        if ($block->getNameInLayout() === 'head') {
            // this will add <link rel="canonical" href="http://your-url.com">
            $block->addLinkRel('canonical', 'http://your-url.com');

            // If you need more attributes on the link tag use addItem instead
            // This will add <link rel="canonical" href="http://your-url" attr="Your Attribute">
            // $block->addItem('link_rel',  'http://your-url', 'rel="canonical" attr="Your Attribute"')
        }
    }
}

更新

由于核心head.phtml模板文件运行echo $this->getChildHtml()(渲染所有子项),因此可以通过添加core/text块作为子项来插入标记并向其添加文本字符串(就像你已经尝试过使用xml)。如果addItem不能满足您的需求,则可以更灵活,因为您可以通过这种方式插入任何字符串。用

替换$block->addLinkRel
$canonical = $block->getLayout()->createBlock('core/text')
    ->setText('<link rel="canonical" href="http://your-url.com">')
$block->append($canonical); 
相关问题