Select Page

How to pass data to the js widget in Magento 2

Amir Khan
Published: July 13, 2022

Sometimes we need to pass data to the js file for performing some operations on these values.
With the help of js widget you can pass dynamic data to the js file.
Here we’ll learn how to pass dynamic data using js widget.

We assume our module name is Webkul_Extension and front name is webext.

Step #1 = Create controller to load the layout.
Path = app/code/Webkul/Extension/Controller/Index/Index.php

namespace Webkul\Extension\Controller\Index;
class Index extends \Magento\Framework\App\Action\Action
	protected $_pageFactory;
	public function __construct(
		\Magento\Framework\App\Action\Context $context,
		\Magento\Framework\View\Result\PageFactory $pageFactory
    ) {
		$this->_pageFactory = $pageFactory;
		return parent::__construct($context);
	public function execute()
		return $this->_pageFactory->create();

Step #2 = Describe webpage layout in the layout file. Load the template file which will load js code.
Path = app/code/Webkul/Extension/view/frontend/layout/webext_index_index.xml

<?xml version="1.0"?>
<page xmlns:xsi="" layout="1column" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
        <referenceContainer name="content">
            <block class="Magento\Framework\View\Element\Template" name="WebkulExtension" template="Webkul_Extension::ext_widget.phtml"></block>

Step #3 = Call js widget in template file and provide dynamic data to the js file. Dynamic data will have variable name and value.
Path = app/code/Webkul/Extension/view/frontend/templates/ext_widget.phtml

<div class="customWebExt">
        Example of widget. 244.
    <div class="defaultContent">
        Default content goes here.
    <div class="messageContent">
        No message found.
<script type="text/x-magento-init">
        ".customWebExt": {
            "myExtWidget": {
                "overriddenValue": "Webkul Extension content goes here.",
                "message": " 1 message found."

Step #4 = Declare widget and perform respective operation in the js file.
Path = app/code/Webkul/Extension/view/frontend/web/js/webkul-ext-widget.js

    ], function($){
        $.widget('mage.myCustomWidget', {
            options: {
                overriddenValue: "testing...",
             * Widget initialization
             * @private
             _create: function() {
                 self = this;
    return $.mage.myCustomWidget;

Step #5 = Create requirejs-config.js to map respective js file with alias name.

Path = app/code/Webkul/Extension/view/frontend/requirejs-config.js

var config = {
    "map": {
        "*": {
            "myExtWidget": "Webkul_Extension/js/webkul-ext-widget"

Response :=