Menu Close
    Searching for an experienced Magento 2 Development Company ?

    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 4 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 ! 🙂

    . . .
    Discuss on Helpdesk

    Leave a Comment

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


    Be the first to comment.

    Back to Top