Expand my Community achievements bar.

SOLVED

Render the HTML of a component programatically

Avatar

Community Advisor

Hi 

 

   I have a requirement where I want to render a component/page programatically. Something similar like https://experienceleaguecommunities.adobe.com/t5/adobe-experience-manager/accessing-final-rendered-h...

 

   If I give the path , I should be able get the final HTML for that page or component node. I remember doing this with HTMLPreProcessor or something similar long back in CQ5.4 . But I am not sure how to acheive it now. Anyone have a sample code !? 

 

 

Thanks

Veena

1 Accepted Solution

Avatar

Correct answer by
Level 8

Hello @Veena_Vikram ,
You can try this one, https://gist.github.com/nateyolles/1dc9f8699fce70916764#file-aemresourceresolutionservlet-java 

@Reference
private RequestResponseFactory requestResponseFactory;
@Reference
private SlingRequestProcessor requestProcessor;

public String getRenderedHTML (String path) {
        // Page HTML
        // String path = "/content/my-project/master/en/home.html";
        // Component HTML
        // String path = "/content/my-project/master/en/home/jcr:content/body/my-component.html";
        HttpServletRequest req = requestResponseFactory.createRequest("GET", path);
        WCMMode.DISABLED.toRequest(req);
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        HttpServletResponse resp = requestResponseFactory.createResponse(out);
        requestProcessor.processRequest(req, resp, resourceResolver);
        return out.toString();
    }

 

3 Replies

Avatar

Correct answer by
Level 8

Hello @Veena_Vikram ,
You can try this one, https://gist.github.com/nateyolles/1dc9f8699fce70916764#file-aemresourceresolutionservlet-java 

@Reference
private RequestResponseFactory requestResponseFactory;
@Reference
private SlingRequestProcessor requestProcessor;

public String getRenderedHTML (String path) {
        // Page HTML
        // String path = "/content/my-project/master/en/home.html";
        // Component HTML
        // String path = "/content/my-project/master/en/home/jcr:content/body/my-component.html";
        HttpServletRequest req = requestResponseFactory.createRequest("GET", path);
        WCMMode.DISABLED.toRequest(req);
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        HttpServletResponse resp = requestResponseFactory.createResponse(out);
        requestProcessor.processRequest(req, resp, resourceResolver);
        return out.toString();
    }

 

Avatar

Level 2

@Veena_Vikram This should work as I also have used similar approach in one of our usecase.

page footer