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');
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With