AEM/CQ: Conditional CSS class on decoration tag

你。 提交于 2019-11-30 15:41:38

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);
    }

The Correct way to do is using cq:htmlTag. Create a unstructured node under your component with name cq:htmlTag

Add a property to it "class" of type "String" and the value being "myclass" the class you want to add to your component's wrapper/decorator div.

Refer links:

1) Wrapper Div Manipulation

2) Best link to understand this

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!