Created

Jan 28, 2013

Get child pages based on a template

Posted by Vianney Baron

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

ADD A COMMENT