cancel
Showing results for 
Search instead for 
Did you mean: 

How to add a configurable external JS with additional data- attributes via requirejs?

How to add a configurable external JS with additional data- attributes via requirejs?

Hi guys, I encountered a problem and was stuck for a few days already. I have even created a thread on stackoverflow (https://magento.stackexchange.com/questions/251637/how-to-add-a-configurable-external-js-with-additi...), but not much attention was drawn so far. I do not know if it is appropriate to re-post the thread here, but I really could use some help. Thank you all for your attention and assistance in advance.

1 REPLY 1

Re: How to add a configurable external JS with additional data- attributes via requirejs?

Please try this,

 

There are two ways to include javascript from the template in Magento 2: the <script type="text/x-magento-init"> and the data-mage-init attribute. Either way can be used to pass data to the script within the json definition. For example, using the x-magento-init script tag, in the template you have:

<script type="text/x-magento-init">
    {
        "*": {
            "js/example": {
                "a": "<?php echo 'Hello from template' ?>"
            }
        }
    }
</script>

And in the JS file, you have:

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

    return function (config) {        console.log(config); // will output {a: "Hello from template"}        alert(config.a); // would be equal to alert("Hello from template");
    }
});