Fetching jcr:content properties

Avatar

Avatar

viki1101

Avatar

viki1101

viki1101

18-11-2020

Hello Community - I am using this model for the component to read the properties and perform some action, it is working and I am able to read the properties of the component.

 

@Model(adaptables = { Resource.class, SlingHttpServletRequest.class })

public class Test {
@PostConstruct
public void init() {

Node curNode = this.request.getResource().adaptTo(Node.class);
try {
if (curNode.hasProperty("compId")) {
String compId = curNode.getProperty("compId").getString();
}
}
}
}

I would like to read some additional properties which are required and only available in jcr:content(cq:PageContent) node of the page. I was trying to read using the below but it is not working. Am I doing anything wrong here? Can someone advise on this?

 

ResourceResolver resourceResolver=request.getResourceResolver();
Resource resource=resourceResolver.getResource("/content/testsite/en/homepage/jcr:content");
ValueMap properties = resource.adaptTo(ValueMap.class);
String title = properties.get("jcr:title", (String) null);

 

 

Accepted Solutions (1)

Accepted Solutions (1)

Avatar

Avatar

Anudeep_Garnepudi

Avatar

Anudeep_Garnepudi

Anudeep_Garnepudi

18-11-2020

Hi @viki1101 

You can do that by simply injecting Page Properties into Model. Check the below code.

@Model(adaptables = {Resource.class,SlingHttpServletRequest.class})
public class TestModel {
    @ScriptVariable
    ValueMap pageProperties;

    private pageTitle;

    public String getPageTitle() {
        return pageTitle;
    }
   @PostConstruct
    protected void init() {
        pageTitle = pageProperties.get("jcr:title", "No Title");
    }

}

I am simply returning Page Title.

AG

Answers (1)

Answers (1)

Avatar

Avatar

snbaem

Avatar

snbaem

snbaem

18-11-2020

Can you try something like this below?

@Model(adaptables = { Resource.class, SlingHttpServletRequest.class })

public class Test {
@ScriptVariable
private Page currentPage;
@PostConstruct
public void init() {
Resource currentPageRes = currentPage.adaptTo(Resource.class);

Resource currentPageContentRes = currentPageRes.getChild(JcrConstants.JCR_CONTENT)
ValueMap vm = currentPageContentRes.getValueMap();
String title = vm.get("jcr:title", String.class);



Node curNode = this.request.getResource().adaptTo(Node.class);
try {
if (curNode.hasProperty("compId")) {
String compId = curNode.getProperty("compId").getString();
}
}
}
}