Created
Get child pages based on a template
Sometimes when I need to parse a large CQ website using Java, I want to list the children of a page based on the template. This can be very helpful when creating a carousel displaying featured pages, or working on a search functionnality, as in both cases we need to create a list of pages we want to display back to the user.
There are a few ways to do this: I can use the query builder to create a query based on the cq:template property, but the code can be a bit complex. I could also simply iterate over the children of the page and read the property to create my list, but it's a rather inelegant approach.
So I had a look through the CQ Page API, and found a nice and easy-to-use function for this: listChildren(filter). It fits my requirement perfectly, as I will illustrate here.
Using this function you can leverage an out of the box filter, the PageFilter, as such:
Iterator< Page > it = homePage.listChildren(new PageFilter());
Or create a custom one based on your own requirements. For instance in our case if we want to return the pages using the template named "productpage", we simply have to define the following filter:
class ProductPageFilter implements Filter {
@Override
public boolean includes(Object element) {
Page p = (Page) element;
return (p.getProperties().get(NameConstants.NN_TEMPLATE, "")
.equals("/apps/myapp/templates/productpage"));
}
}
COMMENTS
-
Be aware that from CQ-5.5 p.getTemplate() will always return null on publisher instances.Nice catch Andon! I've amended the code accordingly :)I did a few changes, hope it worksI've amended the code accordingly :)This code worked perfect. I did notice as well that that it will return null but otherwise it is good to go.very informative, you are indeed an expert, thank you for sharing, have a nice dayOczywiście, nie każdy poń może datować się, oraz wprost przeciwnie, elektroniczne papierosy egzystują adresowane tylko do ludzi dorosłych, jakie kauteryzują uprzednio długi okres czasu plus czują wobec tego niedogodność
Comments (7)