Magento 2:在head标签之后添加自定义脚本

San*_*utt 8 php xml magento magento2

我想在head标签开始后添加自定义脚本.

喜欢.

<head>
<script>console.log("I'm loaded!");</script>
Run Code Online (Sandbox Code Playgroud)

我试图在default_head_blocks.xml中添加代码

<referenceContainer name="head.additional">
      <block class="Custom\Module\Block\Success" template="Custom_Module::success/head.phtml"/>
</referenceContainer>
Run Code Online (Sandbox Code Playgroud)

=>输出:

<script>console.log("I'm loaded!");</script>
</head>
Run Code Online (Sandbox Code Playgroud)

此代码在head标记结束之前使用add script.

请检查以下代码

Block => Custom/Module/Block/Onepage/Success.php

namespace Custom\Module\Block\Onepage;
    use Magento\Framework\View\Element\Template;

    class Success extends \Magento\Checkout\Block\Onepage\Success {

    public function getOrder() 
        {
            $objectManager =\Magento\Framework\App\ObjectManager::getInstance();
            $helper = $objectManager->get('Custom\Module\Helper\Data');

            $lastOrderId = $this->getOrderId();

            if (empty($lastOrderId)) 
            {
                return null;
            }
              $orderData = $objectManager->create('Magento\Sales\Model\Order')->loadByIncrementId($this->getOrderId());

            return $orderData;
        }

    }
Run Code Online (Sandbox Code Playgroud)

Helper => Custom\Module\Helper\Data.php

namespace Custom\Module\Helper;
class Data extends \Magento\Framework\App\Helper\AbstractHelper
{

    /**
     * @param \Magento\Framework\App\Helper\Context $context
     */
    protected $_request;

    public function __construct(
        \Magento\Framework\App\Helper\Context $context,
        \Magento\Framework\App\Request\Http $request
    ) {
         $this->_request = $request;
        parent::__construct($context);

    }
     public function getConfigValue($value = '') {
        return $this->scopeConfig
                ->getValue($value,\Magento\Store\Model\ScopeInterface::SCOPE_STORE);
    }
    public function getTemplate()
    {
        if ($this->getConfigValue('custom_general/general/active') == 1) {
            $template =  'Custom_Module::checkout/success.phtml';
        } else {
            $template = 'Magento_Checkout::success.phtml';
        }

        return $template;
    }
}
Run Code Online (Sandbox Code Playgroud)

di.xml => etc\di.xml

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../vendor/magento/framework/ObjectManager/etc/config.xsd">
    <preference for="Magento\Checkout\Block\Onepage\Success" type="Custom\Module\Block\Onepage\Success"/>
</config>
Run Code Online (Sandbox Code Playgroud)

Layout Xml => Custom/Module/view/frontend/layout/default.xml

<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
    <referenceBlock name="require.js">
        <action method="setTemplate">
            <argument name="template" xsi:type="string">Custom_Module::success/head.phtml</argument>
        </action>
    </referenceBlock> 
    </body>
</page>
Run Code Online (Sandbox Code Playgroud)

Template => Custom/Module/view/frontend/templates/success/head.phtml

<script>
    console.log("I'm loaded!");

</script>
Run Code Online (Sandbox Code Playgroud)

请帮帮我解决这个问题

提前致谢.

San*_*pta 9

我不确定这是否正确,但我有一个领先优势.

默认情况下,magento 2会使用该root.phtml文件相应地设置head内容vendor/magento/module-theme/view/base/templates/root.phtml(如果尚未覆盖).

这里,$requireJs变量首先加载到头块中.该$requireJs变量在定义render内部方法Page类-其位于vendor/magento/framework/view/Result/Page.php.

在此文件中,$requireJs包含require.js块.该require.js块定义vendor/Magento/module-theme/view/frontend/layout/default.xml如下:

<block name="require.js" class="Magento\Framework\View\Element\Template" template="Magento_Theme::page/js/require_js.phtml" />
Run Code Online (Sandbox Code Playgroud)

1)复制require_js.phtmlvendor/magento/module-theme/view/frontend/templates/page/js你的主题app/design/frontend/{VENDOR}/{THEME_NAME}/Magento_Theme/templates/page/js/

2)现在您可以像这样添加脚本:

<script>
    console.log("I'm loaded!");

    var require = {
        "baseUrl": "<?php /* @escapeNotVerified */ echo $block->getViewFileUrl('/') ?>"
    };
</script>
Run Code Online (Sandbox Code Playgroud)

更新(使用模块)

覆盖require.js块不是一个优雅的解决方案.如果有人有一个好的解决方案,请回答.现在编辑你的布局xml:

<referenceBlock name="require.js">
    <action method="setTemplate">
        <argument name="template" xsi:type="string">Custom_Module::success/head.phtml</argument>
    </action>
</referenceBlock> 
Run Code Online (Sandbox Code Playgroud)

并在里面success/head.phtml添加你的代码:

<script>
    console.log("I'm loaded!");
    var require = {
        "baseUrl": "<?php /* @escapeNotVerified */ echo $block->getViewFileUrl('/') ?>"
    };
</script>
Run Code Online (Sandbox Code Playgroud)