我刚开始使用Sling模型,但是在父模型中检索子节点属性时遇到问题。 Here is my JCR structure
图像节点是由基础组成的。 我的目标是在Topbanner节点中然后在其可见脚本中获取图像组件的“ filerefernce”属性。 这是我的topbanner节点模型:
@Model(adaptables=Resource.class)
public class TopBanner {
@Self @Via("resource")
private Resource bannerBackGroundImage;
private String bannerBgImagePath;
// @Inject
// private String bannerTitle;
// @Inject
// private String bannerDescription;
//
// @Inject
// private String bannerButtonText;
//
// @Inject
// private String bannerButtonLink;
@SlingObject
private ResourceResolver resourceResolver;
@PostConstruct
public void init() {
TopBanner.LOG.info("we are here");
try {
bannerBackGroundImage=resourceResolver.getResource("/apps/ads/components/structure/TopBanner2/Image");
this.bannerBgImagePath=bannerBackGroundImage.adaptTo(ValueMap.class).get("fileReference",String.class);
} catch(SlingException e) {
TopBanner.LOG.info("Error message **** " + e.getMessage());
}
}
// getters omitted
我得到的错误是 标识符Mypackage.models.TopBanner无法通过Use API正确实例化
答案 0 :(得分:0)
如果您的目标是获取“ fileReference”,请尝试以下操作:
@Self
private SlingHttpServletRequest request;
@ValueMapValue(name = DownloadResource.PN_REFERENCE, injectionStrategy = InjectionStrategy.OPTIONAL)
private String fileReference;
然后获得我们的资产使用权:
if (StringUtils.isNotEmpty(fileReference)) {
// the image is coming from DAM
final Resource assetResource = request.getResourceResolver().getResource(fileReference);
if (assetResource != null) {
Asset asset = assetResource.adaptTo(Asset.class);
//Work with your asset there.
}
}
还添加到您的班级批注:
@Model(adaptables = { SlingHttpServletRequest.class })
答案 1 :(得分:0)
使用@ChildResource
批注
@ChildResource
@Named("image") //Child node name
private Resource childResource;
private String imagePath;
public String getImagePath() {
return imagePath;
}
@PostConstruct
public void init() {
imagePath = childResource.getValueMap().get("fileReference", String.class);
}
使用Sightly / HTL标记检索imagePath
<div data-sly-use.model="package.name.TopBanner">
<img src="${model.imagePath}"/>
</div>
根据Sling documentation文档的另一种方法是使用@Via
注释,因为Sling模型API 1.3.4。
文档中的示例
@Model(adaptables=Resource.class)
public interface MyModel {
// will return resource.getChild("jcr:content").getValueMap().get("propertyName", String.class)
@Inject @Via(value = "jcr:content", type = ChildResource.class)
String getPropertyName();
}