【发布时间】:2018-06-18 10:48:48
【问题描述】:
我想在 head 标签开始后添加自定义脚本。
喜欢。
<head>
<script>console.log("I'm loaded!");</script>
我尝试在 default_head_blocks.xml 中添加代码
<referenceContainer name="head.additional">
<block class="Custom\Module\Block\Success" template="Custom_Module::success/head.phtml"/>
</referenceContainer>
=> 输出:
<script>console.log("I'm loaded!");</script>
</head>
这段代码在head标签结束前使用了add脚本。
请检查以下代码
块 => 自定义/模块/块/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;
}
}
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;
}
}
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>
布局 XML => 自定义/模块/视图/前端/布局/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>
模板 => 自定义/模块/视图/前端/模板/成功/head.phtml
<script>
console.log("I'm loaded!");
</script>
请帮助我解决这个问题
提前致谢。
【问题讨论】: