Sling model to retrieve data from content fragments. | Community
Skip to main content
Level 2
October 29, 2024
Solved

Sling model to retrieve data from content fragments.

  • October 29, 2024
  • 3 replies
  • 1697 views

How to create a sling model which can fetch values from content fragments?

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

3 replies

arunpatidar
Community Advisor
arunpatidarCommunity AdvisorAccepted solution
Community Advisor
October 29, 2024
Tethich
Community Advisor
Community Advisor
October 30, 2024

@jitesh07 

Not sure what your use case is or what exactly you need to achieve at the end.

 

- If you simply need to map some Sling model over some CF, then you need to look at this as like you would map a Sling model on any other Sling resource. Is the same approach. You write a Sling model, you add your Java properties mapping your CF properties, and you give it a path to read from /content/dam/path/to/your/cf/jcr:content/data/... And the example provided by @arunpatidar are more then enough.

 

- If your use case is more about having a way to get CF data in JSON format to consume it in other place, not directly in a Sling model, maybe you can consider exploring other 2 options (JSON Exporter and GraphQL) explained in this thread https://experienceleaguecommunities.adobe.com/t5/adobe-experience-manager/how-to-get-data-from-content-fragment-and-export-in-json-format/m-p/564867

 

GabrielMircea
Level 2
November 4, 2024

Hi @jitesh07 , Its pretty much a resource mapper, doesn't make any difference is a content fragment. Here's an example:

  • Create a Sling Model to represent the Content Fragment structure.
  • Inject the Content Fragment path using @ResourcePath.
  • Adapt the resource to Content Fragment and retrieve the data.
  • Access the data in HTL, displaying the Content Fragment values.

 

 

// The content fragment path, injected from a property or passed dynamically @ResourcePath(name = "contentFragmentPath") private Resource contentFragmentResource; private Map<String, String> fragmentData = new HashMap<>(); @PostConstruct protected void init() { if (contentFragmentResource != null) { ContentFragment contentFragment = contentFragmentResource.adaptTo(ContentFragment.class); if (contentFragment != null) { for (String elementName : contentFragment.getElements()) { FragmentData fragmentDataElement = contentFragment.getElement(elementName).getValue(); fragmentData.put(elementName, fragmentDataElement.toString()); } } } }