Search code examples
apostrophe-cms

How-to access widget data in helper


in my frontend helper I use a parameter and give it everywhere data.widget.

Is it possible to access data.widget in the helper context? I've only found the self.output object tree. But I think that is not a solution with good quality.

Thanks.

Edit for code sample:

Well, in a template you can do something like:

{{ apos.myModuleAlias.iCallAHelper(data.widget) }}

And the part of myModule-widgets/index.js:

construct: function(self, options) {
  self.addHelpers({
    iCallAHelper: function(data) { console.log(data); }
  });
}

Is it possible to access data.widget in the helper without providing data.widget as parameter?


Solution

  • Passing a piece/widget/page to a helper at the template level is pretty common practice, just like your illustrating.

    If your issue is that you always need some special data/decision/format to happen based on a widget, you can override the widget's load method and attach that special something to your widget and then access it in your template.

    widget's index.js

    module.exports = {
        extend: 'apostrophe-widgets',
        ...
        construct: function(self, options) {
            const superLoad = self.load;
            self.load = function (req, widgets, callback) {
                return superLoad(req, widgets, function (err) {
                    if (err) {
                        return callback(err);
                    }
                    // `widgets` is each widget of this type being loaded on a page
                    widgets.forEach(function (widget) {
                        // do something cool, attach it to widget
                        widget.somethingCool = 'hello world';
                    });
                    return callback(null);
                });
            };
        }
    }
    

    You would then be able to access data.widget.somethingCool in your template.