Pass data from one component to another in adobe CQ

孤者浪人 提交于 2019-11-30 18:35:19

问题


I'm using Adobe CQ5. I have made two components that are independent of each other. However, I want to use data from one component in the other one. How do I achieve this? How can I make two components interact with each other?

Thanks in advance.


回答1:


You can use javax.jcr.Node and javax.jcr.Property interface to get properties of another component. For example, you have added component1 and component2 to page1. In the repository you should have structure similar to this:

/content
    /project
        /page1
            /jcr:content
                /parsys
                    /component1
                        /...some properties
                    /component2
                        /...some properties

If you want to get properties of component2 while in component1, you can use something like:

Node parsys = currentNode.getParent();
if(parsys.hasNode("component2")) {
    Node component2 = parsys.getNode("component2");
    if(component2.hasProperty("someProperty"))
      Property someProperty = component2.getProperty("someProperty");
}



回答2:


There are a number of options, depending on how closely the components are coupled (e.g. will both always be placed on the page at the same time? Are they hard-wired into the template, or placed by the editors, etc.)

If both components are on the same page, the simplest is probably to set a variable within one component & read it in another, e.g.:

foo.jsp

<c:set var="globalFooTitle" value="${properties.title}" scope="request"/>

bar.jsp

<c:out value="${globalFooTitle}">[Optional fallback value]</c:out>



回答3:


While there is nothing wrong with @kmb's answer, I almost always prefer to use higher level Apis than lower level ones. In the case of CQ, this means using the sling resource API instead of the JCR node API.

That would look something like this, assuming the same structure of the 2 components on a single page as he laid out.

Resource r = resourceResolver.getResource(currentResource, "../component2");
if(r != null) {
    ValueMap props = r.adaptTo(ValueMap.class);
    String somePropertyValue = props.get("someProperty", "");
}


来源:https://stackoverflow.com/questions/21325733/pass-data-from-one-component-to-another-in-adobe-cq

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!