【问题标题】:AEM/CQ: Conditional CSS class on decoration tagAEM/CQ:装饰标签上的条件 CSS 类
【发布时间】:2014-09-29 14:25:46
【问题描述】:

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

我无法在组件上设置此 CSS 类,因为它取决于组件的实例,我无法在资源上设置它,因为资源可以在多个页面上呈现,并且 CSS 类因页面而异已开启。

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

componentContext.getCssClassNames().add('test-class-1');
component.getHtmlTagAttributes().set('class', 'test-class-2');//throws an exception
currentNode.setProperty('cq:cssClass', 'test-class-3');

【问题讨论】:

    标签: javascript aem


    【解决方案1】:

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

    以下过滤器将my-class 添加到/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);
        }
    

    【讨论】:

    • +1 今天实际使用了这个,效果很好!只有一个注释(在 AEM 6.3.2 上测试):在我们的例子中,我们想在执行 WCMComponentFilter 之前添加我们的类。由于 WCMComponentFilter 的排名为 200,因此“订单”应高于 200。排名越高意味着执行得越早。
    【解决方案2】:

    正确的做法是使用cq:htmlTag。 在您的组件下创建一个名为 cq:htmlTag 的非结构化节点

    向它添加一个“字符串”类型的“类”属性,值是“myclass”,您要添加到组件的包装器/装饰器 div 中的类。

    参考链接:

    1) Wrapper Div Manipulation

    2) Best link to understand this

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-08-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-24
      • 2014-10-22
      • 2019-02-23
      • 2021-10-22
      相关资源
      最近更新 更多