Reputation: 11
Is there a way how I can call the same instance of a model within HTL using the same data? I want to create an object within the model of a page, let's say a String object, and then use it in the model of a component. To create the bean (or model instance), I call
<sly data-sly-use.model="myModel"/>
in the page and in the component Problem is that I have now 2 instances with 2 sets of local data - what I do NOT want to have.
Upvotes: 0
Views: 1069
Reputation: 3951
The SlingHttpServletRequest
(in general) provides an instance of SlingBindings
, which contains a reference to "currentPage"
(I am using the static field WCMBindings.CURRENT_PAGE
[dependency: groupId: com.adobe.cq.sightly
, artifactId: cq-wcm-sightly-extension
, version: 1.2.30
] in my example).
The Optional
I am using in my example is a Java 8 class which can be used to avoid too many checks for null
references.
final Optional<Page> optional = Optional.ofNullable(request)
.map(req -> (SlingBindings) req.getAttribute(SlingBindings.class.getName()))
.map(b -> (Page) b.get(WCMBindings.CURRENT_PAGE));
A simplified/explicit example would be
Page getCurrentPageFromRequest(@Nonnull final SlingHttpServletRequest request) {
final SlingBindings bindings = (SlingBindings) request.getAttribute(SlingBindings.class.getName())
if (bindings == null) {
return null;
}
return (Page) bindings.get(WCMBindings.CURRENT_PAGE);
}
In your Sling model you would just call
@Model(adaptables={ SlingHttpServletRequest.class, })
public class Model {
public Model(@Nonnull final SlingHttpServletRequest request) {
final Page currentPage = getCurrentPageFromRequest(request);
// read properties.
}
Page getCurrentPageFromRequest(@Nonnull final SlingHttpServletRequest request) {
final SlingBindings bindings = (SlingBindings) request.getAttribute(SlingBindings.class.getName())
if (bindings == null) {
return null;
}
return (Page) bindings.get(WCMBindings.CURRENT_PAGE);
}
}
Upvotes: 1