May 22, 2020
Estimated Post Reading Time ~

How to instantiate a Sling Model with multiple adaptables

The @Model annotation in Sling Models allows for multiple adaptables, for example 

@Model(adaptables = { SlingHttpServletRequest.class, Resource.class }) 

However, I am not sure how to instantiate a Model with multiple adaptables from a JSP. The options shown in the Sling documentation always specify a single adaptable only: 
https://sling.apache.org/documentation/bundles/models.html#adaptto

Best How To:
When your model is adaptable from both classes it means you can use any of them, not that you have to adapt both.

So, you adapt it as any other Sling Model. Just it should work with both. In you case you could do

<sling:adaptTo adaptable="${resource}" adaptTo="org.apache.sling.models.it.models.MyModel" var="model"/>

or<sling:adaptTo adaptable="${slingRequest}" adaptTo="org.apache.sling.models.it.models.MyModel" var="model"/>

Still, remember that if you are using injection, not all injectors are available from both adaptables. The request supports more than the resource (anything that comes from the script bindings, currentPage, etc).


By aem4beginner

No comments:

Post a Comment

If you have any doubts or questions, please let us know.