2

How to pass parameter form .phtml to require js file

Template file

<script type="text/javascript">
        require(['Namespace_Module/js/custom'], function () {
        });
</script>

JS file

define(['jquery'], function ($) {

//here need to get parameter

});
1
  • if my answer is helpful to you then you can accept as answer. so it will be useful to another user. Thanks :) Commented Mar 18, 2019 at 11:02

1 Answer 1

2

In your phtml file you can add a parameter as the code below.

<script type="text/x-magento-init">
{
   "*": {
        "Namespace_Modulename/js/myJs": {            
           "customVar": "<?= 'Your parameter'; ?>"
        }
   }
}
</script>

In you js file add below code.

define([
    'jquery',
    'mage/url'
], function ($, url) {
    'use strict';

    return function (config) {

      var customVar = config.customVar;
        console.log(customVar);
      }
});

In above code customVar is equal to you need to pass your parameter, you can pass multiple parameters to create a new variable.

I hope it helps!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.