Quantcast
Channel: Webkul Blog
Viewing all articles
Browse latest Browse all 5490

Add Dynamic Scripts to any Layout in Magento 2

$
0
0

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


Viewing all articles
Browse latest Browse all 5490

Trending Articles