Shopware6 Loading options from twig template to Js plugin

Viewed 112

I have been following https://developer.shopware.com/docs/guides/plugins/plugins/storefront/add-custom-javascript to create a javascript plugin. But, I am struggling with adding options through twig template. I have something like the following:

Twig file : product.html.twig:

{% set contentModalOptions = {
            cmsContentId: "some-hash",
            navigationUrl: path('frontend.cms.page'),
            failSafeRedirectUrl: '/some-failsafe-url/'
        } %}

        <div>
            <a target="_self" href="#" data-content-modal="true" data-content-modal-options="{{ contentModalOptions|json_encode|escape('html_attr') }}">
                help text
            </a>
        </div>

plugin file : custom-plugin.js:

import Plugin from 'src/plugin-system/plugin.class';

export default class ContentModalPlugin extends Plugin {

    static options = {
        cmsContentId: '',
        navigationUrl: '',
        failSafeRedirectUrl: ''
    };

    init() {
        console.log(this);
        console.log(this.options); // empty values
    }
}

Notes:

  • In the browser, I see that values set using twig as the HTML attribute.
  • Plugin has been registered and works with the template.

console.log() in the plugin doesn't print any values that are set from twig. It just shows the options object that has been initialized in the plugin.

Any help is appreciated.

2 Answers

I assume you register the plugin like this:

PluginManager.register('ContentModal', ContentModalPlugin, '[data-content-modal]');

Within the constructor of the Plugin class this.options = this._mergeOptions(options); should then called, which in turn parses the data-${dashedPluginName}-options attribute. It should throw an error if it can't parse the json:

`The data attribute "data-${dashedPluginName}-options" could not be parsed to json: ${e.message}`

Are the any errors when you look at the console of your browsers dev tools?

For further debugging you could also try calling super._mergeOptions(this.options); from your init method.

Now, I see what the problem was. When I registered my plugin, I had the following:

PluginManager.register('ContentModalPlugin', ContentModalPlugin, '[data-content-modal]');

So, I tried passing the options with data-content-modal-options attribute through twig but it seems that the resolved plugin name in _mergeOptions() at src/plugin-system/plugin.class takes the plugin name (i.e the string that is the first argument of the register function) and not the attribute definition in the register method.

So, adding a html attribute as data-content-modal-plugin-options based on my class name resolved the problem.

Related