4

I have a JS file that is loaded through require-js.config. I need to get access to a store->configurations value inside my JS file.

Does anyone know of a way to accomplish that?

1

1 Answer 1

7

If we take a look at onepage phtml template, we can see how to set and get a global config Js variable.

vendor/magento/module-checkout/view/frontend/templates/onepage.phtml

...... 
    <script>
        window.checkoutConfig = <?php /* @escapeNotVerified */ echo \Zend_Json::encode($block->getCheckoutConfig()); ?>;
        // Create aliases for customer.js model from customer module
        window.isCustomerLoggedIn = window.checkoutConfig.isCustomerLoggedIn;
        window.customerData = window.checkoutConfig.customerData;
    </script>
......

We can do the same way by setting a global Js variable.

For example, in your template:

<script>
   window.valuesConfig = '<?php /* @escapeNotVerified */ echo $block->getValuesConfig(); ?>'
</script>

And then, in your custom js, you can get:

getValues: function() {
                return window.valuesConfig;
}

Remember add the method in your block, for example:

public function getValuesConfig()
{
        return $this->_scopeConfig->getValue('get/value/config');
}
2
  • 2
    Technically, yes this is an answer to my question. I'll accept it as the answer. But I was looking for something more elegant than just dumping out global variables for the world to see onto the page. Aug 7, 2016 at 23:52
  • As far as I know, Magento 2 also use local storage feature. We can also add the config to local storage. Aug 8, 2016 at 14:13

Your Answer

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

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