Expand my Community achievements bar.

Don’t miss the AEM Skill Exchange in SF on Nov 14—hear from industry leaders, learn best practices, and enhance your AEM strategy with practical tips.
SOLVED

How to use content fragment api in react?

Avatar

Level 4

How to use content fragment as headless in react?

1 Accepted Solution

Avatar

Correct answer by
Level 5

As you may have seen the responses making it obvious that the solution is tailored based on use case you have. If you are using react spa using aem spa editor integration probably approach is going to be as simple as allowing your front end map a generic component to the content fragment aem component and from the response you can read the model path to determine what react component to render. But if your app is a standalone app with no aem spa editor in use, you case use asset api to call the cf using its path and consume in your react component. And if the content is dynamic based on certain parameters graphql is the ideal way. Choosing this path reduces amt or custom code. Hope this insights help you. Thanks 

View solution in original post

6 Replies

Avatar

Community Advisor

Do you think you can take advantage from GraphQl for this purpose?

I am not sure what is your use case but there are many ways to consume Content Fragment(CF) data thru react or any other js stuff:

1. If your cf content can be cached, in this case you can author the CF with an AEM component, read the date thru java put in window object or use adobe dataLayer(if already implemented) as part of the page source then read the window object or adobe datalayer thru React component.

2. if not to be cached, then use model.json with CF path to read the CF data in react component directly.

Hope this will answer your query.

Umesh Thakur

Avatar

Level 4

Thank you for the reply @Umesh_Thakur .

Basically, I want to use CF with model.json path and use that API in react and not graphql API.

Avatar

Administrator

Creating a servlet or a Sling model to read content fragments and serialize them into JSON in Adobe Experience Manager (AEM) involves several steps. Below, I'll provide an example of how you can create a simple Sling model for this purpose. This example assumes that you have already created a Content Fragment Model and a JSON Exporter Configuration in AEM.

  1. Create a Sling Model Class:

    First, create a Java class for your Sling model. This class will be responsible for fetching content fragments and serializing them into JSON. Below is a basic example:

     
    package com.example.core.models;
    
    import org.apache.sling.api.SlingHttpServletRequest;
    import org.apache.sling.api.SlingHttpServletResponse;
    import org.apache.sling.api.servlets.SlingAllMethodsServlet;
    import org.apache.sling.models.annotations.Default;
    import org.apache.sling.models.annotations.Model;
    import org.apache.sling.models.annotations.injectorspecific.SlingObject;
    import org.apache.sling.models.annotations.injectorspecific.ValueMapValue;
    import org.apache.sling.models.factory.ModelFactory;
    import org.json.JSONArray;
    import org.json.JSONObject;
    
    import javax.servlet.Servlet;
    import javax.servlet.ServletException;
    import java.io.IOException;
    
    @Model(adaptables = SlingHttpServletRequest.class)
    public class ContentFragmentServlet extends SlingAllMethodsServlet {
        @ValueMapValue
        @default(values = "YourContentFragmentPath")
        private String contentFragmentPath;
    
        @SlingObject
        private SlingHttpServletRequest request;
    
        @SlingObject
        private SlingHttpServletResponse response;
    
        @Override
        protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException {
            try {
                // Fetch the Content Fragment based on the provided path
                org.apache.sling.api.resource.Resource contentFragmentResource = request.getResourceResolver().getResource(contentFragmentPath);
    
                if (contentFragmentResource != null) {
                    // Create a JSON representation of the Content Fragment
                    JSONObject contentFragmentJSON = new JSONObject();
                    contentFragmentJSON.put("title", contentFragmentResource.getValueMap().get("title", ""));
                    // Add more properties as needed
    
                    // Write the JSON to the response
                    response.setContentType("application/json");
                    response.setCharacterEncoding("UTF-8");
                    response.getWriter().write(contentFragmentJSON.toString());
                } else {
                    response.sendError(404, "Content Fragment not found");
                }
            } catch (Exception e) {
                response.sendError(500, "Internal Server Error");
            }
        }
    }
    
  2. Configure the Servlet:

    Next, you need to configure the servlet in AEM. You can do this by creating an OSGi configuration for the servlet. Here is an example of how to configure it:

    • Create a sling:OsgiConfig node under /apps/<your_project>/config (or a similar location).
    • Define the configuration properties for your servlet, including the servlet path and any other required settings.

    Here is an example of a servlet configuration in JSON format:

    {
        "sling.servlet.methods": ["GET"],
        "sling.servlet.paths": ["/bin/contentfragment"],
        "sling.servlet.extensions": "json",
        "service.ranking": 100
    }
    

    In this example, the servlet is mapped to the path /bin/contentfragment and configured to respond to GET requests with the .json extension.

  3. Access the Servlet from Your SPA:

    In your SPA, you can make an HTTP GET request to the servlet endpoint (e.g., /bin/contentfragment) to retrieve the serialized JSON data.

Please note that this is a basic example to get you started. You should adapt it to your specific requirements, error handling, and security considerations. Additionally, ensure that you have appropriate permissions and security measures in place for accessing content fragments and executing servlets in your AEM instance.



Kautuk Sahni

Avatar

Correct answer by
Level 5

As you may have seen the responses making it obvious that the solution is tailored based on use case you have. If you are using react spa using aem spa editor integration probably approach is going to be as simple as allowing your front end map a generic component to the content fragment aem component and from the response you can read the model path to determine what react component to render. But if your app is a standalone app with no aem spa editor in use, you case use asset api to call the cf using its path and consume in your react component. And if the content is dynamic based on certain parameters graphql is the ideal way. Choosing this path reduces amt or custom code. Hope this insights help you. Thanks