首页 > 解决方案 > Magento 2 - 扩展 onepage.phtml 以添加自定义 JS

问题描述

Magento 2

我创建了一个自定义送货方式模块,需要在设置送货地址和送货方式的结帐页面中添加自定义 JS。但这对我不起作用。

onepage.phtml在以下位置添加了我自己的:

My_Module\view\frontend\templates\onepage.phtml

我还在checkout_index_index.xml以下位置创建了一个文件:

My_Module\view\frontend\layout\checkout_index_index.xml

我的 JS 的位置:

My_Module\view\frontend\web\js\custom.js

我的onepage.phtml文件内容:

<script type="text/javascript">
        require(['jquery', 'custom-js'], function($) {
            alert('JS loaded');
        });
</script>

我的checkout_index_index.xml文件内容:

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceBlock name="checkout.onepage">
            <action method="setTemplate">
                <argument name="template" xsi:type="string">My_Module::onepage.phtml</argument>
            </action>
        </referenceBlock>
    </body>
</page>

我的requirejs-config.js文件内容:

var config = {
    map: {
        '*': {
            custom-js: 'My_Module/js/custom-js'
        }
    }
};

我的module.xml文件内容:

<?xml version="1.0"?>
  <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="My_Module" setup_version="1.0.1">
        <sequence>
            <module name="Magento_Checkout"/>
        </sequence>
    </module>
  </config>

当我将onepage.phtml文件的内容添加到核心onepage.phtml文件时,JS 会正确加载。

另外,当我在文件中referenceBlock name更改为时,我的 JS 文件被加载,但似乎只有文件被渲染,没有别的......我使用了错误的值吗?checkout.rootcheckout_index_index.xmlonepage.phtmlname

有没有更好的方法来包含 JS 或者我只是错过了什么?任何帮助,将不胜感激!

标签: phpmagentoe-commerce

解决方案


推荐阅读