Render the HTML of a component programatically | Community
Skip to main content
VeenaVikraman
Community Advisor
Community Advisor
May 15, 2023
Solved

Render the HTML of a component programatically

  • May 15, 2023
  • 1 reply
  • 1104 views

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-html-of-component-through-service/m-p/165883

 

   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

This post is no longer active and is closed to new replies. Need help? Start a new post to ask your question.
Best answer by Sady_Rifat

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(); }

 

1 reply

Sady_Rifat
Community Advisor
Sady_RifatCommunity AdvisorAccepted solution
Community Advisor
May 15, 2023

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(); }

 

Level 3
May 15, 2023

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

VeenaVikraman
Community Advisor
Community Advisor
May 15, 2023

Thank you @sady_rifat and @sateeshkreddy it worked.