Search code examples
shopwareshopware6shopware6-app

Shopware6 Loading options from twig template to Js plugin


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.


Solution

  • 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.