Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AEM/CQ: Conditional CSS class on decoration tag

Tags:

javascript

aem

How can I dynamically set a CSS class on the wrapping decoration tag of an AEM6 Sightly component?

I cannot set this CSS class on the component as it depends on the instance of the component, and I can't set it on the resource as the resource can be rendered on multiple pages and the CSS class differs depending on which page it is on.

I've tried the following 3 techniques inside the JavaScript Use-API with no success:

componentContext.getCssClassNames().add('test-class-1');
component.getHtmlTagAttributes().set('class', 'test-class-2');//throws an exception
currentNode.setProperty('cq:cssClass', 'test-class-3');
like image 934
Alasdair McLeay Avatar asked Jan 09 '23 17:01

Alasdair McLeay


1 Answers

The decoration tag is added by a filter (namely the WCMComponentFilter) before the component is actually rendered, so it isn't possible to change it inside the component code. In order to use some logic to dynamically set a CSS class on this decorator, you need to create a custom filter, that will run before the WCMComponentFilter and set appropriate properties to the IncludeOptions attribute.

Following filter adds my-class to all carousel components under /content/geometrixx/en.

@SlingFilter(scope = SlingFilterScope.COMPONENT, order = -300)
public class DecoratorFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        boolean addClass = false;
        if (request instanceof SlingHttpServletRequest) {
            final SlingHttpServletRequest slingRequest = (SlingHttpServletRequest) request;
            final Resource resource = slingRequest.getResource();
            final String resourceType = resource.getResourceType();
            final String resourcePath = resource.getPath();

            // put any custom logic here, eg.:
            addClass = "foundation/components/carousel".equals(resourceType)
                    && resourcePath.startsWith("/content/geometrixx/en");
        }
        if (addClass) {
            final IncludeOptions options = IncludeOptions.getOptions(request, true);
            options.getCssClassNames().add("my-class");
        }
        chain.doFilter(request, response);
    }
like image 75
Tomek Rękawek Avatar answered Jan 12 '23 08:01

Tomek Rękawek