How to get child pages of a component using sling model?
A developer is creating a custom component on the page and needs to list all the child pages of the root page. How to do that and what is the correct way to do that?
A developer is creating a custom component on the page and needs to list all the child pages of the root page. How to do that and what is the correct way to do that?
A good sample! except that it's better always to use try-with-resources as the resource resolver is of Closeable interface, and the ArrayList should be used instead of the default LinkedList only in limited cases when you need to update the list after filling it.
In addition from me, if you use those pages to build a list of links, you should check for other properties, for example, if the page is a redirect one, you should display the target page instead of found one, and also if you need to traverse no only first children, but a whole tree, I use this approach:
// public final class StreamUtils {
public static Stream<Page> descendants(@Nullable final Page rootPage) {
return Optional.ofNullable(rootPage).map(rootPage ->
Stream.concat(Stream.of(rootPage),
StreamSupport.stream(Spliterators.spliteratorUnknownSize(rootPage.listChildren(),
Spliterator.ORDERED), false)
.flatMap(StreamUtils::descendants)))
.orElse(Stream.empty());
}I have inlined some utility functions that I use to get it shorter, I hope I didn't brake it as I did it right here not in IDE 😅 And then I use this function as:
final List<Page> allDescendantPages = StreamUtils.descendants(rootPage).collect(Collectors.toList());
Enter your E-mail address. We'll send you an e-mail with instructions to reset your password.