Expand my Community achievements bar.

Radically easy to access on brand approved content for distribution and omnichannel performant delivery. AEM Assets Content Hub and Dynamic Media with OpenAPI capabilities is now GA.
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
Community Advisor

Hello @VeenaVikraman ,
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();
    }

 

View solution in original post

3 Replies

Avatar

Correct answer by
Community Advisor

Hello @VeenaVikraman ,
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 3

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