我对AEM和6.1版本相对较新。我试图根据可创作的文件路径列出孩子,但似乎无法弄清楚。以前,我有类似的东西
<sly data-sly-list.child="${currentPage.getParent.listChildren}" data-sly-unwrap>...</sly>
它按预期工作。现在,我需要使它更通用,但是
<sly data-sly-list.child="${properties.filePath.listChildren}" data-sly-unwrap>...</sly>
不循环访问。我想我需要使用"资源"对象,但不确定如何。我可以直接在 Sightly 通话中使用它吗?还是必须创建/编辑当前的 Java 文件?提前感谢!
我建议您使用Sling Model
将子项列表返回到HTL模板。以下代码是基于您提供的少量信息的此类模型的简单版本:
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.models.annotations.Optional;
import org.apache.sling.models.annotations.Model;
import org.apache.sling.models.annotations.injectorspecific.ValueMapValue;
import org.apache.sling.models.annotations.injectorspecific.OSGiService;
import java.util.Collections;
@Model(adaptable = Resource.class)
class MyModel {
@ValueMapValue
@Optional
private String filePath;
@OSGiService
private ResourceResolver resourceResolver;
public Iterator<Resource> getChildren() {
if (this.filePath == null || this.filePath.isEmpty()) { // Use StringUtils.isBlank() if you can.
return Collections.emptyIterator();
}
final Resource resource = this.resourceResolver.getResource(this.filePath);
if (resource == null) {
return Collections.emptyIterator();
}
return resource.listChildren();
}
}
您的 HTL 模板可能如下所示:
<sly data-sly-use.model="my.package.MyModel">
<sly data-sly-list.child="${model.children}" data-sly-unwrap>...</sly>
</sly>
言论:
- 应
@Optional
filePath
,因为存在尚未配置组件但已实例化模型的边缘情况。例如:编辑器将组件添加到页面,但尚未打开并保存编辑对话框。组件将被渲染,模型将被实例化,但filePath
将被null
。 - 显然,您的 HTL 模板可能看起来有点不同。
您将无法在HTL中直接执行此操作,因为properties.filePath
返回String
,并且String类中没有listChildren
方法。
前面的 currentPage.getParent
返回一个Page
,该反过来在调用 listChildren
方法时返回一个Iterator<Page>
。
由于 HTL 目前不允许你调用带参数的方法,你可能需要使用 Java Use API 或 JS Use API 来处理这种情况。
要了解有关 HTL 和使用 API 的更多信息,请参阅此文档。