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
  • Your issue solved? Commented Aug 6, 2016 at 14:38

1 Answer 1

8

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. Commented 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. Commented Aug 8, 2016 at 14:13

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.