Search code examples
shopware6

How to access shopware app configuration in JavaScript file?


how do I access the shopware app (not plugin) configuration inside a JavaScript file. The way for twig files is:

{{ config('myApp.config')|json_encode() }}

What is the right way to do this in Resources/app/storefront/src located files?

Thanks.


Solution

  • You'll have to pass the data from the template by using data attributes of the element you register your storefront JS plugin to. The plugin base offers automatic setting of the options property, based on a naming convention. This can be done by adding the -options suffix to a data attribute, named according to the plugin name, and using valid JSON for the value.

    {% set myPluginData = config('myApp.config') %}
    
    <div data-my-custom-plugin="true"
         data-my-custom-plugin-options="{{ myPluginData|json_encode }}">
    </div>
    
    class MyCustomPlugin extends Plugin {
        init() {
            // should log your plugin config
            console.log(this.options);
        }
    
        // ...
    }
    
    PluginManager.register('MyCustomPlugin', MyCustomPlugin, '[data-my-custom-plugin]');