Magento 1 - 通过布局更新 xml 代码将内联 javascript 添加到产品页面
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23906109/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Magento 1 - add inline javascript to product page via layout update xml code
提问by wutzebaer
Hi i want to use google analytics's AB-Testing engine. Therefore i have to add a javascript-snippet to single product pages.
嗨,我想使用谷歌分析的 AB 测试引擎。因此,我必须向单个产品页面添加一个 javascript 代码段。
My intend was to add it in the description or short-description. It is working, but it is insufficient, because the script makes a redirect, which means the page loads half and then is redirected.
我的意图是将其添加到说明或简短说明中。它正在工作,但还不够,因为脚本进行了重定向,这意味着页面加载了一半然后被重定向。
Google says i should add the script in the head-tag. Is it possible to insert the script as "custom layout update" here:
Google 说我应该在 head-tag 中添加脚本。是否可以在此处将脚本作为“自定义布局更新”插入:
i could imagine something like
我可以想象出类似的东西
<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>
回答by Gerard de Visser
It's cleaner to load the javascript from file. You do not necessarily need all that blocks but can do it like:
从文件加载 javascript 更干净。您不一定需要所有这些块,但可以这样做:
<default translate="label" module="page">
<reference name="head">
<action method="addJs"><script>path/to/script.js</script></action>
</reference>
</default>
Path is relative path from js
folder in magento root.
路径是js
magento 根目录中文件夹的相对路径。
To add javascript to xml directly (which I do not recommend) you can use CDATA, like:
要将 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>
回答by wutzebaer
my solution was to extend the head block:
我的解决方案是扩展头部块:
<?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;
}
}
now i can use it like that
现在我可以这样使用它
<reference name="head">
<action method="addInlineJs"><script>alert('cool');</script></action>
</reference>