【问题标题】:Magento 1 - add inline javascript to product page via layout update xml codeMagento 1 - 通过布局更新 xml 代码将内联 javascript 添加到产品页面
【发布时间】:2014-07-17 08:26:04
【问题描述】:

您好,我想使用谷歌分析的 AB 测试引擎。因此,我必须将 javascript-sn-p 添加到单个产品页面。

我打算将它添加到描述或简短描述中。它正在工作,但还不够,因为脚本会进行重定向,这意味着页面加载一半然后被重定向。

Google 说我应该在 head-tag 中添加脚本。是否可以在此处将脚本作为“自定义布局更新”插入:

我可以想象类似的东西

<default translate="label" module="page">
        <label>All Pages</label>
        <block type="page/html" name="root" output="toHtml" template="page/3columns.phtml">
            <block type="page/html_head" name="head" as="head">
                <action method="addJs"><script>alert('hello')</script></action>
            </block>
        </block>
</default>

【问题讨论】:

    标签: javascript xml magento layout


    【解决方案1】:

    从文件加载 javascript 更简洁。您不一定需要所有这些块,但可以这样做:

    <default translate="label" module="page">   
        <reference name="head">
            <action method="addJs"><script>path/to/script.js</script></action>
        </reference>
    </default>
    

    路径是magento根目录中js文件夹的相对路径。

    要直接将javascript添加到xml(我不推荐),您可以使用CDATA,例如:

    <reference name="head">
        <block type="core/text" name="your.block.name">
            <action method="setText">
                <text><![CDATA[<script type="text/javascript">alert('hello');</script>]]></text>
            </action>
        </block>
    </reference>
    

    【讨论】:

    • 但是每个产品的 js 都是独一无二的。我不想为每个产品添加文件
    • 我应该为哪个块做settext?我不想移除头块的其余部分
    • 您可以为此添加自己的自定义块。编辑我的答案给你示例代码。
    • 这仅适用于 Magento 1,调整了标题。对于 Magento 2,您应该提出不同的问题。
    【解决方案2】:

    我的解决方案是扩展头块:

    <?php
    class Company_Modulename_Block_Html_Head extends Mage_Page_Block_Html_Head {
        public function addInlineJs($name)
        {
            $this->addItem('inlinejs', $name);
            return $this;
        }
    
        public function getCssJsHtml()
        {
            $html = parent::getCssJsHtml();
    
            foreach ($this->_data['items'] as $item) {
                if($item['type']=='inlinejs') {
                    $html .= sprintf('<script type="text/javascript">%s</script>' . "\n", $item['name']);
                }
            }
    
            return $html;
        }
    }
    

    现在我可以这样使用它了

    <reference name="head">
           <action method="addInlineJs"><script>alert('cool');</script></action>
    </reference>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多