14

In magento 1

we can call this prototype function in phtml for example

function ABC(){
     var a = '<?php echo $a;?>'
    alert(a);
 }

but in magento 2 we can not add this type of function in phtml,for that we have to create requirejs-config.js

var config = {
map: {
    '*': {
        'exam': 'js/example',
    }
}
};

like this and example.js

 function ABC(){

    alert(a);
 }

in phtml

require(['jquery','exam'], function($){
    var a= <?php echo $a; ?>;
});

I am trying to pass variable like this but its not working,how to pass variable from phtml to external js in magento 2

3 Answers 3

25

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");
    }
});
5
  • I am using this code, but my alert is popping up twice, however if I write an alert before "return function (config) {" it pops up only one, I can't find why the alerts inside "return function (config) {" are coming twice. Dec 6, 2016 at 12:05
  • Great info, but how would I gain access to the data in the config object from another js file? For example, if I sent the above data – '"a": "<?php echo 'Hello from template' ?>" to a js/model/example.js file, how would I then pull that data into a view/sample.js file? Many thanks!
    – MikeMason
    Mar 27, 2017 at 21:26
  • Trying to pass data around between different .js files seems like it probably wouldn't work. You could just pass the data to both files' configs in the template. Or, if you have some data you want to be accessible to various js files, you could use Magento's 'private content 'mechanism: devdocs.magento.com/guides/v2.0/config-guide/cache/… which is what is used internally for the mini-cart, customer data, compare products, etc. Mar 27, 2017 at 23:14
  • 3
    As a side note, if you try this and it doesn't work make sure you are using define and not require. This doesn't work when using require.
    – Ben Crook
    Oct 4, 2017 at 10:20
  • @ Aaron Allen Very Good answer Oct 11, 2017 at 10:48
1

You can pass the variable by using js Widget

Vendor: Rbj Module: DemoWidget app/code/Rbj/DemoWidget/view/frontend/layout/demo_index_index.xml

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<body>
    <referenceContainer name="content">
        <block class="Magento\Framework\View\Element\Template" name="demo.page" template="Rbj_DemoWidget::magento-widget.phtml"></block>
    </referenceContainer>
</body>

app/code/Rbj/DemoWidget/view/frontend/requirejs-config.js

var config = {
    "map": {
        "*": {
            "myCustomWidget": "Rbj_DemoWidget/js/my-custom-widget"
        } 
    }
};

app/code/Rbj/DemoWidget/view/frontend/web/js/my-custom-widget.js

define([
'jquery',
'jquery/ui'
], function($){
    $.widget('mage.myCustomWidget', {
        options: {
            abcd: 1,
            passvalue:'test'
        },
        /**
         * Widget initialization
         * @private
         */
         _create: function() {
            alert(this.options.passvalue);  // custom message
            alert(this.options.abcd); // 123
        }
    });
return $.mage.myCustomWidget;
});

app/code/Rbj/DemoWidget/view/frontend/templates/magento-widget.phtml

<div class="maindiv">
    <div class="secondary">
        Widget Example using Magento 2
    </div>
<div> 
<script type="text/x-magento-init">
{
    ".maindiv": {
        "myCustomWidget": {
            "passvalue": "custom message",
            "abcd": 123
        }
    }
}
</script>

Vote this answer up if it helps.

0

data-mage-init Example

<div data-mage-init='{"js/example": { "message": "<?= 'Hello from template' ?>"}}'>
    <a title="<?= $block->escapeHtml(__('Show Info')) ?>"
       class="action action-info ral-surcharge-info"
    >
        <i class="fas fa-info"></i>
    </a>
</div>

JS:

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

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

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.