i want to add custom script just after the start of head tag.
like.
<head>
<script>console.log("I'm loaded!");</script>
i tried to add code in default_head_blocks.xml
<referenceContainer name="head.additional">
<block class="CustomModuleBlockSuccess" template="Custom_Module::success/head.phtml"/>
</referenceContainer>
=> output :
<script>console.log("I'm loaded!");</script>
</head>
this code are using add script before the end of head tag.
Please check Below code
Block => Custom/Module/Block/Onepage/Success.php
namespace CustomModuleBlockOnepage;
use MagentoFrameworkViewElementTemplate;
class Success extends MagentoCheckoutBlockOnepageSuccess {
public function getOrder()
{
$objectManager =MagentoFrameworkAppObjectManager::getInstance();
$helper = $objectManager->get('CustomModuleHelperData');
$lastOrderId = $this->getOrderId();
if (empty($lastOrderId))
{
return null;
}
$orderData = $objectManager->create('MagentoSalesModelOrder')->loadByIncrementId($this->getOrderId());
return $orderData;
}
}
Helper => CustomModuleHelperData.php
namespace CustomModuleHelper;
class Data extends MagentoFrameworkAppHelperAbstractHelper
{
/**
* @param MagentoFrameworkAppHelperContext $context
*/
protected $_request;
public function __construct(
MagentoFrameworkAppHelperContext $context,
MagentoFrameworkAppRequestHttp $request
) {
$this->_request = $request;
parent::__construct($context);
}
public function getConfigValue($value = '') {
return $this->scopeConfig
->getValue($value,MagentoStoreModelScopeInterface::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 => etcdi.xml
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../vendor/magento/framework/ObjectManager/etc/config.xsd">
<preference for="MagentoCheckoutBlockOnepageSuccess" type="CustomModuleBlockOnepageSuccess"/>
</config>
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>
Template => Custom/Module/view/frontend/templates/success/head.phtml
<script>
console.log("I'm loaded!");
</script>
Please help me and solve this issue
Thanks in advance.
2
Answers
I am not sure if this is the correct way or not, but I have got a lead.
By default magento 2 usees the
root.phtml
file to setuphead
content accordingly, which is located invendor/magento/module-theme/view/base/templates/root.phtml
(if it has not been overridden).Here, the
$requireJs
variable is loaded first in the head block. The$requireJs
variable is defined in therender
method insidePage
class -which is located invendor/magento/framework/view/Result/Page.php
.In this file,
$requireJs
contains therequire.js
block. And therequire.js
block is defined invendor/Magento/module-theme/view/frontend/layout/default.xml
:Solution
1) Copy
require_js.phtml
fromvendor/magento/module-theme/view/frontend/templates/page/js
to your themeapp/design/frontend/{VENDOR}/{THEME_NAME}/Magento_Theme/templates/page/js/
2) Now you can add your script like this:
UPDATE (Using Module)
Overriding the
require.js
block is not an elegant solution. if anyone has a good solution please answer. For now edit your layout xml:and inside
success/head.phtml
add your code:I found a simple way of doing it that seems very reasonable, because it uses existing features in the
adminhtml
theme without any need to override/intercept anything.Background
Like @sanchit-gupta mentioned, the
root.phtml
template is used as the basis to render both thefrontend
andadminhtml
areas, and so is the associated classMagentoFrameworkViewResultPage
, which always looks for a block namedhead.additional
before rendering.This block exists in the
frontend
layouts by default, but unfortunately it doesn’t exist in theadminhtml
layout.Solution
With that in mind, the current best way (as of 2.3.x) to add inline
<scripts>
to theadminhtml
‘s<head>
section is to add anyhead.additional
block: it will be automatically rendered by the framework. It either has to be aListText
block so that it renders all it’s children automatically, or aTemplate
with a specified template file. I actually chose too nest my actual block inside theListText
block just to keep the same mechanism available as in thefrontend
area (i.e. for compatibility with other plugins that might be doing the same).Example
In your custom module or theme, add a layout update that inserts the following block into the
body
of the page layout (which is just to do it the same way as it’s done in Magento 2 core for thefrontend
area):Done! Your template will render inside
<head></head>
– without any awkward overrides or “hacks”.What’s more, if other modules also reference
head.additional
in theadminhtml
area, they will be compatible with your code.