CQ access deep child node's property from current node (current component)

sefirosu picture sefirosu · Jun 18, 2014 · Viewed 14.5k times · Source

i am working on a carousel component called "tabbedcarousel", i need to iterate through it's children nodes to access an image property. see the pic below:

enter image description here

that "tabbedimagecarouselunselectedimage" -> "fileReference" is what i need to get.

say i m currently working on "tabbedcarousel.jsp", i have access to my currentNode, so the way i m assuming to get the deep child img property is like this:

<%


        NodeIterator tabbedCarouselChildNodes = currentNode.getNodes();
        while(tabbedCarouselChildNodes.hasNext()){
            Node parNode = tabbedCarouselChildNodes.nextNode();

            NodeIterator parChildNodes = parNode.getNodes();
            while(parChildNodes.hasNext()){
                Node tabbedCarouselItemNode = parChildNodes.nextNode();

                NodeIterator tabbedCarouselItemChildNodes = tabbedCarouselItemNode.getNodes();
                while(tabbedCarouselItemChildNodes.hasNext()){
                    Node tabImgNode = tabbedCarouselItemChildNodes.nextNode();
                    %>
                    test here s the img property : <%= tabImgNode.getProperties("fileReference").toString()%> !!!
                    <% 
            }
        }

%>

but it does not work. hopefully someone can give me some suggestions. thanks

Answer

Tomek Rękawek picture Tomek Rękawek · Jun 18, 2014

I've added one brace at the end and replaced tabImgNode.getProperties() with hasProperty()/getProperty() combo. Works fine on my CQ:

<%
NodeIterator tabbedCarouselChildNodes = currentNode.getNodes();
while(tabbedCarouselChildNodes.hasNext()) {
    Node parNode = tabbedCarouselChildNodes.nextNode();
    NodeIterator parChildNodes = parNode.getNodes();
    while(parChildNodes.hasNext()){
        Node tabbedCarouselItemNode = parChildNodes.nextNode();
        NodeIterator tabbedCarouselItemChildNodes = tabbedCarouselItemNode.getNodes();
        while(tabbedCarouselItemChildNodes.hasNext()){
            Node tabImgNode = tabbedCarouselItemChildNodes.nextNode();
            if (!tabImgNode.hasProperty("fileReference")) {
                continue;
            }
%>
test: <%= tabImgNode.getProperty("fileReference").getString()%>
<% 
        }
    }
}
%>

BTW, it can be refactored using Sling API:

<%
Iterator<Resource> items = resource.getChild("par").listChildren();
while (items.hasNext()) {
    Resource property = items.next().getChild("tabimageunselectedimage/fileReference");
    if (property == null) {
        continue;
    }
%>
fileReference: <%= property.adaptTo(String.class) %>
<% } %>

The third option is to use 3rd party library called SlingQuery:

<% for (Resource r : SlingQuery.$(resource).find("#tabimageunselectedimage")) { %>
  path: <%= r.adaptTo(ValueMap.class).get("fileReference") %>
<% } %>