Expand my Community achievements bar.

SOLVED

How do I convert a page into a model

Avatar

Level 2

Newbie here, so go easy. Not quite sure my terminology is correct.

I'm trying to get all of the instances of a given model.  I have a Video component like so:

@Model(adaptables = Resource.class, defaultInjectionStrategy = DefaultInjectionStrategy.OPTIONAL)

public class Video {

     private url;

}

I'd like to get all instances of Video models. By convention, I can put all of my video pages in one location in the JCR tree. Then I can get all the video Page objects like so:

    videoPages = new ArrayList<>();

    allVideosRootPage.listChildren(page -> page.getContentResource() != null)

            .forEachRemaining(videoPages::add);

But how do I actually get the models from those page objects?

1 Accepted Solution

Avatar

Correct answer by
Employee Advisor

When rendering a page, you typically adapt parts of the repository tree into models for easier handling. Just build the Model as documented on the Sling site and then you can turn any resource (well, not any, but only just the matching ones) into your model.

Model myModel = resource.adaptTo(Model.class);

(don't forget to check myModel for not being null, which would indicate that the adaption did not work, mostly because the resource cannot be turned into the model because of missing or incorrect injections.)

If you want to collect all Videos, adapt all resources being a video to your Video class; the problem, that you need to find all video resources first does not go away with this approach.

Jörg

View solution in original post

2 Replies

Avatar

Level 10

This is not clear - most likely why no one answered it. Models are typically setup for components. Those components are then placed on pages.

Avatar

Correct answer by
Employee Advisor

When rendering a page, you typically adapt parts of the repository tree into models for easier handling. Just build the Model as documented on the Sling site and then you can turn any resource (well, not any, but only just the matching ones) into your model.

Model myModel = resource.adaptTo(Model.class);

(don't forget to check myModel for not being null, which would indicate that the adaption did not work, mostly because the resource cannot be turned into the model because of missing or incorrect injections.)

If you want to collect all Videos, adapt all resources being a video to your Video class; the problem, that you need to find all video resources first does not go away with this approach.

Jörg