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

  • By Andon Sikavica - 10:08 AM on Jan 29, 2013   Reply
    Be aware that from CQ-5.5 p.getTemplate() will always return null on publisher instances.
    • By Vianney Baron - 11:10 AM on Jan 29, 2013   Reply
      Nice catch Andon! I've amended the code accordingly :)
      • By hotels da nang - 4:03 AM on Feb 23, 2013   Reply
        I did a few changes, hope it works
        • By diễn đàn seo - 2:47 PM on Apr 16, 2013   Reply
          I've amended the code accordingly :)
          • By nj limo - 1:59 PM on Apr 26, 2013   Reply
            This code worked perfect. I did notice as well that that it will return null but otherwise it is good to go.
            • By Lowongan Kerja 2013 - 2:31 PM on May 18, 2013   Reply
              very informative, you are indeed an expert, thank you for sharing, have a nice day
              • By katalog stron - 8:05 AM on May 27, 2013   Reply
                Oczywiś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ść

                ADD A COMMENT