AEM / CQ:装饰标签上的条件CSS类 [英] AEM/CQ: Conditional CSS class on decoration tag

查看:110
本文介绍了AEM / CQ:装饰标签上的条件CSS类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在AEM6 Sightly组件的包装装饰标签上动态设置CSS类?

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

我无法在组件上设置此CSS类,因为它取决于该组件的实例,并且我无法在资源上设置它,因为该资源可以在多个页面上呈现,并且CSS类根据它所在的页面而有所不同。

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.

我已经在JavaScript Use-API中尝试了以下3种技巧,但均未成功:

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


推荐答案

装饰标签由过滤器添加(即 WCMComponentFilter )在实际呈现组件之前,因此无法在组件代码中对其进行更改。为了使用某种逻辑在此装饰器上动态设置CSS类,您需要创建一个自定义过滤器,该过滤器将在 WCMComponentFilter 之前运行,并将适当的属性设置为 IncludeOptions 属性。

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.

以下过滤器将 my-class 添加到 / content / geometrixx / en 下的所有轮播组件。

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

这篇关于AEM / CQ:装饰标签上的条件CSS类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆