如何在Magento扩展中添加自定义JavaScript

时间:2015-04-24 19:55:02

标签: javascript php xml magento magento-1.9

我正在尝试向标记<head>内的所有Magento页面添加javascript。我在此文件夹树中有一个名为example.xml的文件(我在etc/config.xml上进行了配置,以使用自定义.xml文件,如example.xml):

--design
----frontend
------base
--------default
----------layout
------------example.xml

我正在使用两种方法来做到这一点。第一个是(不工作):

<layout>
<default>
    <reference name="head">
        <action method="addJs">
            <script>folder/myjavascript.js</script>
        </action>
    </reference>
</default>
</layout>

第二个是(仅适用于结帐页面):

<layout>
    <example_handle>
        <reference name="head">
            <action method="addJs">
                <script>folder/myjavascript.js</script>
            </action>
        </reference>
    </example_handle>

    <checkout_onepage_index>
        <update handle="example_handle"/>
    </checkout_onepage_index>

    <onepagecheckout_index_index>
        <update handle="example_handle"/>
    </onepagecheckout_index_index>

    <opc_index_index>
        <update handle="example_handle"/>
    </opc_index_index>

    <aw_onestepcheckout_index_index>
        <update handle="example_handle"/>
    </aw_onestepcheckout_index_index>
</layout>

我的javascript有一个片段,我需要从Magento获取自定义变量(在php中我使用getConfigData('api_key'))。所以,我的第二个问题是:是否可以直接从javascript获取此值,或者我需要使用php执行此操作?

var _api_key = ?`getConfigData('api_key')`?;

1 个答案:

答案 0 :(得分:0)

如果你想执行php代码,那么需要调用phtml 这个调用phtml文件作为头部的参考块。

<example_handle>
    <reference name="head">
       <block type="core/template" template="page/myjavascript.phtml" name="myjavascript" />
    </reference>
</example_handle>

然后在phtml(app/design/frontend/YOUR_PACKAGE/YOUR_TEMPATE/template/page/myjavascrpt.phtml)上编写php代码:并将myjavascript.js的所有代码放到这个phtml中。

然后在<?php echo $this->getChildHtml('myjavascript');?>

中致电head.phtml