Expand my Community achievements bar.

How to render the content fragemnet data on page in AEM using sling model

Avatar

Level 3

Hi All,

I'm Anil kumar

I have created a content fragment with data fields name, image and biodata. and a component with cFPicker.

I have authored the component with cfPath.Below is my sling model to extract the fragment data on page
but its not working as expected, can any one help me !

package com.gehealthcare.core.internal.models.content.v1;

import com.gehealthcare.core.models.content.SampleGridModel;
import com.gehealthcare.core.models.content.SampleGridItems;
import lombok.Getter;
import org.apache.commons.lang3.StringUtils;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.models.annotations.DefaultInjectionStrategy;
import org.apache.sling.models.annotations.Model;
import org.apache.sling.models.annotations.injectorspecific.ChildResource;
import org.apache.sling.models.annotations.injectorspecific.SlingObject;
import org.apache.sling.models.annotations.injectorspecific.ValueMapValue;

import javax.annotation.PostConstruct;
import java.util.Collections;
import java.util.List;

@getter
@Model(adaptables = Resource.class,
adapters = SampleGridModel.class,
resourceType = SampleGirdImpl.RESOURCE_TYPE,
defaultInjectionStrategy = DefaultInjectionStrategy.OPTIONAL)
public class SampleGirdImpl implements SampleGridModel {

protected static final String RESOURCE_TYPE ="gehealthcare/components/content/samplegrid/v1/samplegrid"; //NOSONAR

@ValueMapValue
private String eyebrow;

@ValueMapValue
private String title;

@ValueMapValue
private String[] fragmentPath;

@ChildResource(name ="gridItems")
public List<SampleGridItems> gridItems = Collections.emptyList();

@SlingObject
private ResourceResolver resourceResolver;

private String fragmentData;

@PostConstruct
protected void init() {
if (fragmentPath != null && fragmentPath.length > 0) {
Resource fragmentResource = resourceResolver.getResource(fragmentPath[0]);
if (fragmentResource != null) {
// Assuming that the Content Fragment has a property named 'data'
fragmentData = fragmentResource.getValueMap().get("data", StringUtils.EMPTY);
}
}
}

@Override
public String getEyebrow() {
return StringUtils.isNotBlank(eyebrow) ? eyebrow.replaceAll("</?p>", StringUtils.EMPTY) : StringUtils.EMPTY;
}

@Override
public String getTitle() {
return StringUtils.isNotBlank(title) ? title.replaceAll("</?p>", StringUtils.EMPTY) : StringUtils.EMPTY;
}

public String getFragmentData() {
return fragmentData;
}
}


  

Topics

Topics help categorize Community content and increase your ability to discover relevant content.

9 Replies

Avatar

Community Advisor

@Anilkumar9 

 

What is the exact issue you are facing with above code?

You can refer to this blog post, it might help

https://aem4beginner.blogspot.com/fetch-content-fragment-using-sling-model

Avatar

Level 3

I'm unable to extract the content fragment data with the above code 

Avatar

Level 4

Hi @Anilkumar9

 

After fetching the fragment data, you need to adapt to content fragment and iterate over the content elements like below.

 

private HashMap<String, Object> myObj = new HashMap<>();
ContentFragment fragment = fragmentResource.adaptTo(ContentFragment.class);
if (Objects.requireNonNull(fragment).getTemplate() != null
&& (fragment.getTemplate().getTitle()).equals(YOUR_CF_NAME)) {
Iterator<ContentElement> elements = fragment.getElements();
ContentElement element;
while (elements.hasNext()) {
element = elements.next();
myObj.put(element.getName(), element.getValue().getValue());
}
}

 

Avatar

Community Advisor

HI @Anilkumar9 ,

Your Sling model looks generally well-structured for fetching data from a content fragment and rendering it on a page. However, there are a few things to consider and potentially adjust:

  1. Ensure Correct Resource Path:

    • Verify that the fragmentPath field is correctly populated with the path to your content fragment. It seems you're expecting an array of paths, but if it's just one path, you might want to change the type from String[] to String.
  2. Check Property Name:

    • Ensure that "data" is the correct property name within your content fragment to fetch the desired data. If you're unsure, you can check the property name in CRXDE Lite or the AEM Content Fragment editor.
  3. Handle Data Retrieval:

    • If "data" is a complex property (like a JSON or XML structure), you might need to parse it accordingly to extract the specific data you want to render on the page. If it's a simple string, then your approach should work fine.
  4. Error Handling:

    • Add proper error handling in case the content fragment path is not found or if the "data" property is missing or empty.
  5. Rendering in Sightly/HTL:

    • Make sure you're correctly rendering the data in your Sightly/HTL component. If fragmentData is a complex structure, you might need to iterate through it or access its properties accordingly.
  6. Debugging:

    • If the data is still not rendering as expected, consider adding log statements or using a debugger to inspect the values of fragmentPath and fragmentData during runtime to identify any issues.
  7. Model Registration:

    • Ensure that your model is registered correctly and that the SampleGridImpl class is correctly referenced in the component's sling:resourceSuperType or via the cq:dialog of the component.

By addressing these points and possibly debugging further, you should be able to resolve any issues with fetching and rendering the content fragment data on your page.




Avatar

Level 7

Thanks ChatGPT, I've been following you, and this is considered spamming, I am reporting you. 

You should have a word with the administrators, this is getting out of hand. It's just very disrespectful to the community... You should really stop.. Spamming is not good, and also shows us that you are not a professional because anyone can use chat GPT to post questions on the query.

Avatar

Level 6

Hi @Anilkumar9 ,

Can u check if u are resourceResolver is not null? Are u getting any errors check in error logs.

Avatar

Administrator

@Anilkumar9 Did you find the suggestion helpful? Please let us know if you require more information. Otherwise, please mark the answer as correct for posterity. If you've discovered a solution yourself, we would appreciate it if you could share it with the community. Thank you!



Kautuk Sahni