Expand my Community achievements bar.

SOLVED

Sling model to retrieve data from content fragments.

Avatar

Level 2

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

1 Accepted Solution

Avatar

Correct answer by
Community Advisor
3 Replies

Avatar

Correct answer by
Community Advisor

Avatar

Level 5

@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-conte...

 

Avatar

Level 2

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