jcrslingsightlysling-models

SlingModel not mapping the JCR properly


I have a SlingModel called TextModel.

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

    @Inject
    private String heading;

    @Inject
    private String description;

    public String getHeading() {
        return heading;
    }

    public String getDescription() {
        return description;
    }
}

I also have a template in Sightly which renders the component:

<div data-sly-use.model="project.components.slingmodels.text.TextModel" data-sly-unwrap/>
<div>
    <p>PageModel component</p>
    <h1>${model.heading}</h1>
    <p>Description: ${model.description}</p>
</div>

Then I embed the component in a page:

<div data-sly-resource="${@ resourceType='project/components/textModel'}" data-sly-unwrap></div>

And create the initial JCR structure via JSON:

{
    "jcr:primaryType": "nt:unstructured",
    "sling:resourceType": "project/pages/page",
    "title" : "Welcome page",
    "jcr:content" : {
        "myContent" : {
            "jcr:primaryType": "nt:unstructured",
            "sling:resourceType" : "project/components/textModel",
            "heading": "Heading",
            "description": "test description"
        }
    }
}

All the fields are properly saved in JCR, but my Sling Model returns null as a value of both heading and description.

But, when I create the content like this:

{
    "jcr:primaryType": "nt:unstructured",
    "sling:resourceType": "project/pages/page",
    "title" : "Welcome page",
    "heading": "Heading",
    "description": "test description",
    "jcr:content" : {
        "myContent" : {
            "jcr:primaryType": "nt:unstructured",
            "sling:resourceType" : "project/components/textModel"
        }
    }
}

It works. The JSON is stored under jcr_root/content/hello.json in my project files and I am opening a localhost:8080/content/hello.html URL in my browser.


Solution

  • You should include your component with the right path, otherwise the path points to the current resource and this resource is the jcr:content of the current page.

    <div data-sly-resource="${ @path='componentPath', 
    resourceType='project/components/textModel'}" data-sly-unwrap></div>