php variable

How to pass PHP variables from phtml files to RequireJs in Magento 2?

In Magento 2, we can use Declarative notation to pass dynamic PHP values to RequireJs from template files. Magento templates support <script type=”text/x-magento-init”> … </script> tag to fulfill this requirement.

First, create a module e.g.Webiins_ExitPopup and add a file exitpopup.phtml at locationapp/code/Webiins/ExitPopup/view/frontend/templates to add declarativenotation:

<script type="text/x-magento-init">
            {
                "*": {
                    "Webiins_ExitPopup/js/exitpopup": {
                    "popup_cookie": "<?php echo $popup_cookie ?>",
                    "popup_position": "<?php echo $popupPosition ?>"
                    }
                }
            }
    </script>

We can access these parameters in app/code/Webiins/ExitPopup/view/frontend/web/js/exitpopup.js file:

/**
 * Webiins
 *
 */
define([
    'jquery'
], function ($) {
    'use strict';
    return function(config) {
        console.log(config.popup_cookie);
        var popup_cookie = config.popup_cookie;
        var popup_position = config.popup_position;  
       // we can then use these variables to implement functionality
    };
});