AEM:注入多个组件的通用组件如何具有动态价值

问题描述

我有一个通用组件,可以通过data-sly-resource注入多个组件中。

componentA

<div
  data-sly-resource="${ 'abc' @ resourceType = 'btplayer-cms/components/content/some-common-component' }">
</div>

componentB

<div
  data-sly-resource="${ 'xyz' @ resourceType = 'btplayer-cms/components/content/some-common-component' }">
</div>

在some-common-component.html中,需要将一个“类”添加到div中,该类将是动态的并且特定于它从中注入的组件。例如,当此组件添加到componentA中时 的HTML将是: <div class="componenta-button"></div>添加到componentB中时,它将为<div class="componentb-button"></div>

我该如何实现?我怎么知道谁在注入这个组件,或者如何从父组件发送额外的参数,而我可以从some-common-component.html

访问

解决方法

在这种情况下,最好使用HTL templates

<sly data-sly-use.common="common.html" data-sly-call="${common.myTemplate @ buttonClass='myClassA'}"></sly>
,

您可以使用requestAttributes(refer here

组件A(传递值):

漂亮:

<sly data-sly-use.compA = "com.mysite.core.models.CompA"/>
<div
  data-sly-resource="${ 'abc' @ resourceType = 'btplayer-cms/components/content/some-common-component',requestAttributes = compA.attribute }">
</div>

吊带型号:

包com.realogy.sir.core.models;

import java.util.HashMap; 导入java.util.Map;

import javax.annotation.PostConstruct;

导入org.apache.sling.api.SlingHttpServletRequest; 导入org.apache.sling.models.annotations.Model;

@Model(adaptables = SlingHttpServletRequest.class) 公共类CompA {

public Map<String,Object> attribute = new HashMap<>();

@PostConstruct
protected void init() {
    attribute.put("attributeVal","componenta");
}

}

组件B(传递值):

漂亮:

<sly data-sly-use.compB = "com.mysite.core.models.CompB"/>
<div
  data-sly-resource="${ 'xyz' @ resourceType = 'btplayer-cms/components/content/some-common-component',requestAttributes = compB.attribute }">
</div>

吊带型号:

包com.realogy.sir.core.models;

import java.util.HashMap; 导入java.util.Map;

import javax.annotation.PostConstruct;

导入org.apache.sling.api.SlingHttpServletRequest; 导入org.apache.sling.models.annotations.Model;

@Model(adaptables = SlingHttpServletRequest.class) 公共类CompB {

public Map<String,"componentb");
}

}

通用组件(使用值):

漂亮:

<sly data-sly-use.commonComp= "com.mysite.core.models.CommonComp"/>
<div class="${[commonComp.attributeVal,'button'] @ join='-'}"></div>

吊带型号:

package com.mysite.core.models;

import javax.inject.Inject;

导入org.apache.sling.api.SlingHttpServletRequest; 导入org.apache.sling.models.annotations.Model;

@Model(adaptables = SlingHttpServletRequest.class) 公共类CommonComp {

@Inject @Optional @Default(values="component")
private String attributeVal;

public String getAttributeVal() {
    return attributeVal;
}

}