Page Root Provider
This hidden gem in ACS AEM Commons provides a reliable way for code to determine the homepage of any request. Though Adobe Experience Manager (AEM) provides some alternate methods to guess at the homepage based on the URL structure, Page Root Provider is the only way to reliably get the homepage regardless of how your site paths are structured. Though the tool has many direct uses by developers, it also serves as the foundation to other ACS AEM Commons features such as Shared Component Properties and Contextual Path Browser.
At face value the Page Root Provider is quite basic, performing a single, focused job of determining the homepage for a given request/resource. However, being able to simply and reliably perform that task regardless of path structure enables many higher-level objectives, and on multi-site implementations allows for those objectives to be accomplished without repeating code.
Beyond supporting the ACS AEM Commons features referenced above, other use cases we’ve seen for Page Root Provider include:
- Calculating the homepage link for a header/footer component used across multiple sites on a multi-site platform.
- Creating a component type-based service that executes upon content (e.g. searches blog articles) limited to the current website.
- Determining the current page relative path, omitting hidden portions of the URL (e.g. /content/mysite/language-masters/en)
How to Use
1. Configure the Page Root Provider Service
Configure the ACS AEM Commons service for Page Root Provider by adding an OSGi factory config for `com.adobe.acs.commons.wcm.impl.PageRootProviderConfig`. The configuration is very flexible, allowing for multiple configurations to be provided, multiple paths to be configured, and paths to include regular expressions.
See the example below, where I’ve configured paths to detect the homepage on all international instances of a theoretical “NewCo” website, including a configuration for the style guide included with all Bounteous builds.
2. Inject the OSGi Service Into Your Code
As a standard OSGi service, the Page Root Provider can be easily injected into your custom code whether it’s a sling model, servlet, or other OSGi service by referencing the `com.adobe.acs.commons.wcm.PageRootProvider` interface.
Injection into a sling model:
Injection into an OSGi service/servlet:
3. Fetch the homepage
Given a sling resource (often the resource of the current request, but it doesn’t have to be) call the appropriate Page Root Provider method to get a `com.day.cq.wcm.api.Page` object or path representing the homepage.
Voilà! You now have a reliable way for code to determine the homepage of any request, regardless of how your site paths are structured.