I need to get the component node and here's how the component can be available on the page:
page-->jcr:content-->root-->component
page-->jcr:content-->root-->responsivegred-->component
page-->jcr:content-->root-->responsivegred-<anyrandom number>-->component
page-->jcr:content-->root-->responsivegred-->container-->component
I have the path till root and I want to fetch the comp node. What could be an efficient way?
Solved! Go to Solution.
Views
Replies
Total Likes
Hi @Shaheena_Sheikh,
Below are the ways:
As you have mentioned your /content/page/jcr:content/root, use this below code:
Node pageNode = resolver.getResource(PATH).adaptTo(Node.class);
if (pageNode != null) {
NodeIterator pageNodeIterator = pageNode.getNodes();
while (pageNodeIterator.hasNext()) {
Node individualNode = pageNodeIterator.nextNode();
if (individualNode != null && individualNode.hasNode("COMPONENT NAME")) {
}
If there is no component in that node, you can check if that node has child and repeat the same code above.
Hope this helps!
Thanks,
Kiran Vedantam.
Hi @Shaheena_Sheikh,
Below are the ways:
As you have mentioned your /content/page/jcr:content/root, use this below code:
Node pageNode = resolver.getResource(PATH).adaptTo(Node.class);
if (pageNode != null) {
NodeIterator pageNodeIterator = pageNode.getNodes();
while (pageNodeIterator.hasNext()) {
Node individualNode = pageNodeIterator.nextNode();
if (individualNode != null && individualNode.hasNode("COMPONENT NAME")) {
}
If there is no component in that node, you can check if that node has child and repeat the same code above.
Hope this helps!
Thanks,
Kiran Vedantam.
Hi,
thanks for the answer. Will the above code give me the component node, irrespective of the depth (in which the comp is present)?
Because if you see my question, the comp may not be directly present under the root.
You can use the below snippet in HTL, and it will return the path:
${resource.path}
Thanks!
Hi @Shaheena_Sheikh - Do you want to fetch the component path from a page based on the resource type?
If yes, there are 2 ways. With the help of a query or with node iteration.
With query - Since you know the root path already, construct a query similar to below and this will return the exact component path.
path=/content/we-retail/us/en/men/jcr:content
property=sling:resourceType
property.value=weretail/components/content/title
With node iteration - From the parent root path, iterate until you find a matching component resource. You would need to run the comparison on all the siblings and child nodes here.
resource.listChildren() method can be used to get all the child resources, and you can compare it for your component resource type by using the method isResourceType().
Coming to efficiency, node iteration should be ideally faster if you don't have too many children nodes. If you observe that it is taking time you can implement the query solution.
Thanks,
Fani
Views
Likes
Replies