Webkul
Services
Technologies Bagisto QloApps
iOS Android SAP BigCommerce Wix
Trusted by
Samsung Intel Toyota Walmart Disney Nokia Nestlé Decathlon
See all customers
Back to Top
DEV

Add Dynamic Scripts to any Layout in Magento 2

We will learn how to add a script or style file that requires some dynamic data and parameters before rendering on the page.

Firstly, we will add following code in our layout xml file.

<referenceBlock name="head.additional">
    <block class="Webkul\Test\Block\Head" name="test_scripts_add" />
</referenceBlock>

Then we will create the block mentioned above.

<?php

namespace Webkul\Test\Block;
 
use Magento\Framework\View\Element\Template;
 
class Head extends Template
{
    /**
     * @var \Magento\Framework\View\Asset\Repository
     */
    protected $assetRepository;
 
    /**
     * Header constructor.
     * @param Template\Context $context
     * @param \Magento\Framework\View\Page\Config $pageConfig
     * @param array $data
     */
    public function __construct(
        Template\Context $context,
        \Magento\Framework\View\Page\Config $pageConfig,
        array $data = []
    ) {
        parent::__construct($context, $data);
        $this->pageConfig = $pageConfig;
        $this->manageScripts();
    }
 
    /**
     * @return void
     */
    public function manageScripts()
    {
        // additional attributes goes here
        $attributes = [];

        $this->pageConfig->addRemotePageAsset(
                "https://www.test.com/js?client-id=xyz",
                'js',
                $attributes
            );
        }
    }
}

The important method above is addRemotePageAsset()

This method accepts 3 parametes.

addRemotePageAsset($url, $contentType, array $properties = [])

$url -> the dynamic url for the script or style file.

$contentType -> whether it is a js file or css file.

$array -> additional parameters

Happy Coding ! 🙂

. . .

Leave a Comment

Your email address will not be published. Required fields are marked*


Be the first to comment.

Back to Top

Message Sent!

If you have more details or questions, you can reply to the received confirmation email.

Back to Home