AEM中ArticleContainer内HTL表格组件的标题标签动态切换问题
问题根源
你之前的逻辑失效是因为:当表格组件嵌套在ArticleContainer容器内时,table.firstPosition==true判断的是该组件在容器内部的位置,而非整个页面的顶部位置。即使容器本身在页面最顶部,表格的firstPosition也只是表示它是容器里的第一个子组件,而非页面的第一个组件,所以会始终触发非topOfPage条件。
解决方案一:容器组件传递位置参数给子组件
这是最直接高效的方案,让ArticleContainer先判断自身是否在页面顶部,再将“是否为页面顶部第一个子组件”的参数传递给表格组件:
修改ArticleContainer的HTL代码:
在容器渲染子组件时,判断容器是否在页面顶部,同时判断当前子组件是否是容器的第一个元素,将这两个条件的结果合并后传递给子组件:<!-- ArticleContainer的HTL --> <sly data-sly-test.containerIsTop="${component.firstPosition == true}"/> <sly data-sly-repeat.child="${resource.children}" data-sly-call="${child @ isPageTop=containerIsTop && childList.first}"/>修改表格组件的HTL代码:
接收容器传递的isPageTop参数,动态生成H1/H2标签,避免重复代码:<!-- 表格组件的HTL --> <sly data-sly-test.topOfPage="${isPageTop}"/> <${topOfPage ? 'h1' : 'h2'} data-sly-test="${table.headerCopy}" class="heading fontH2 headingLinear headingThick"> <span class="tableHeadingWrapper">${table.headerCopy @ context='html'}</span> </${topOfPage ? 'h1' : 'h2'}>
解决方案二:表格组件通过Sling Model判断页面位置
如果容器传递参数的方式不可行,可以通过Java模型遍历页面资源树,直接判断表格组件是否处于页面顶部的容器内:
编写Sling Model:
注入当前资源和资源解析器,遍历页面内容的子资源,找到第一个ArticleContainer,并检查当前表格是否是该容器的第一个子组件:package com.yourproject.models; import org.apache.sling.api.resource.Resource; import org.apache.sling.api.resource.ResourceResolver; import org.apache.sling.models.annotations.Model; import org.apache.sling.models.annotations.injectorspecific.Inject; @Model(adaptables = Resource.class) public class TablePositionModel { @Inject private Resource currentResource; @Inject private ResourceResolver resolver; public boolean isTopOfPage() { // 定位到页面的jcr:content节点 Resource pageContent = currentResource.getParent(); while (pageContent != null && !"cq:PageContent".equals(pageContent.getResourceType())) { pageContent = pageContent.getParent(); } if (pageContent == null) { return false; } // 遍历页面子资源,找到第一个ArticleContainer for (Resource child : pageContent.getChildren()) { if ("your-project/components/article-container".equals(child.getResourceType())) { // 检查当前表格是否是该容器的第一个子组件 return child.getChildren().iterator().hasNext() && child.getChildren().iterator().next().getPath().equals(currentResource.getPath()); } } return false; } }修改表格组件的HTL代码:
使用上述模型获取位置判断结果,动态生成标题标签:<!-- 表格组件的HTL --> <sly data-sly-use.positionModel="com.yourproject.models.TablePositionModel"/> <sly data-sly-test.topOfPage="${positionModel.isTopOfPage}"/> <${topOfPage ? 'h1' : 'h2'} data-sly-test="${table.headerCopy}" class="heading fontH2 headingLinear headingThick"> <span class="tableHeadingWrapper">${table.headerCopy @ context='html'}</span> </${topOfPage ? 'h1' : 'h2'}>
注意事项
- 优先选择方案一,因为容器直接判断自身位置的性能更高,避免了表格组件遍历整个页面资源树的开销。
- 替换代码中的
your-project/components/article-container为你项目中ArticleContainer组件的实际资源类型路径。
内容的提问来源于stack exchange,提问作者Matt Moran
相关产品推荐
相关产品推荐

