Search code examples
javascriptapostrophe-cmsnunjucks

Access template options in module's construct method


In Apostrophe, I have a custom module where I would like to pass an option from the Nunjucks apos.area call to the construct method of the widget itself. Concretely, I want to adjust the output of getWidgetWrapperClasses based on the options passed to the module in the template. Is this possible?

Here's an example of what I would like to achieve:

lib/modules/example-widgets/index.js

module.exports = {
    extend: "apostrophe-widgets",
    label: "Example widget",
    construct: function(self, options) {
        self.getWidgetWrapperClasses = function(widget) {
            // templateOptions would be the options object as defined
            // in home.html below
            return ["column", "column-" + templateOptions.width];
        };
    }
};

lib/modules/apostrophe-pages/views/pages/home.html

{% extends "layout.html" %}

{% block content %}
    <div id="widgets">

        {{ apos.area(data.page, "example", {
            widgets: {
                "example": {
                    width: "half"
                }
            }
        }) }}

    </div>
{% endblock %}

Solution

  • I solved this by not using the getWidgetWrapperClasses method, but instead extending the widget wrapper template and overriding a Nunjucks block in there. This is in fact a documented approach if you look in lib/modules/apostrophe-areas/views/widgetBase.html in Apostrophe's code.

    I changed lib/modules/example-widgets/index.js like this:

    module.exports = {
        extend: "apostrophe-widgets",
        label: "Example widget",
        wrapperTemplate: "wrapper",
        construct: function(self, options) {
            // Do something
        }
    };
    

    Then, I added a lib/modules/example-widgets/views/wrapper.html file. In that file, you can simply override the extraWrapperClasses block to add the classes you want, all the while having access to the template options through data.options.

    {% extends "apostrophe-areas:widget.html" %}
    
    {% block extraWrapperClasses %}column column-{{ data.options.width }}{% endblock %}