2

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.

RK1
  • 429
  • 2
  • 7
  • 28

2 Answers2

1

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>
d33t
  • 1,143
  • 6
  • 15
1

I suggest to use:

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

or even better:

<sly data-sly-resource="${'myContent' @ resourceType='project/components/textModels'}"></sly>
luke-w
  • 11
  • 2