How to instantiate a Sling Model with multiple adaptables

3.9k views Asked by At

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

1

There are 1 answers

1
santiagozky On BEST ANSWER

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)