在父节点吊索模型中获取基础组件属性

问题描述 投票:0回答:2

我刚开始使用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 

我得到的错误是Identifier Mypackage.models.TopBanner无法通过Use API正确实例化

aem sling jcr sling-models
2个回答
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 })

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();

}
© www.soinside.com 2019 - 2024. All rights reserved.