SlingModel没有正确映射JCR

时间:2016-06-06 08:20:07

标签: jcr sling sightly sling-models

我有一个名为TextModel的SlingModel。

@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;
    }
}

我还在Sightly中有一个模板,它呈现组件:

<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>

然后我将组件嵌入页面中:

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

通过JSON创建初始JCR结构:

{
    "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"
        }
    }
}

所有字段都正确保存在JCR中,但我的Sling Model返回null作为headingdescription的值。

但是,当我创建这样的内容时:

{
    "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"
        }
    }
}

有效。 JSON存储在我的项目文件中的jcr_root/content/hello.json下,我在浏览器中打开localhost:8080/content/hello.html URL。

2 个答案:

答案 0 :(得分:1)

您应该使用正确的路径包含组件,否则路径指向当前资源,此资源是当前页面的jcr:content。

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

答案 1 :(得分:1)

我建议使用:

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

甚至更好:

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