How to create a sling model which can fetch values from content fragments?
Solved! Go to Solution.
Views
Replies
Total Likes
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-conte...
Hi @Jitesh07 , Its pretty much a resource mapper, doesn't make any difference is a content fragment. Here's an example:
// 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());
}
}
}
}
Views
Likes
Replies
Views
Likes
Replies