如何在HTL(Sightly)中直接获取AEM组件Sling Model导出的JSON数据
方案1:HTL原生序列化(最推荐,零额外代码)
HTL内置支持将Sling Model对象直接序列化为JSON,输出结果和你访问Sling Exporter端点返回的结构完全一致,不需要修改任何Java代码,直接在组件HTL文件中写如下代码即可:
<!-- 首先适配你已经定义好的Sling Model --> <sly data-sly-use.proofPoints="你的包名.ProofPointsModel"> <!-- 直接输出JSON,context='json'会自动完成序列化和安全转义 --> <script type="application/json" id="proofPointsData"> ${proofPoints @ context='json'} </script> </sly>
如果需要把JSON直接暴露给前端JS变量,也可以直接写:
<script> const proofPointsData = ${proofPoints @ context='json'}; </script>
方案2:复用Sling Exporter配置(适合有自定义序列化规则的场景)
如果你给@Exporter配置了自定义的字段过滤、序列化规则、Jackson特性等,想要完全复用这些配置,可以在Sling Model中新增一个默认方法直接返回序列化后的JSON字符串:
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.sling.models.annotations.DefaultInjectionStrategy; import org.apache.sling.models.annotations.Exporter; import org.apache.sling.models.annotations.Model; import javax.inject.Inject; import java.util.List; @Model(adaptables = { Resource.class }, defaultInjectionStrategy = DefaultInjectionStrategy.OPTIONAL, resourceType = "XXX/components/content/XXX") @Exporter(name = "jackson", extensions = "json") public interface ProofPointsModel { @Inject List<ProofPointsList> getProofPoint(); // 新增默认方法返回序列化后的JSON default String getSerializedJson() throws JsonProcessingException { return new ObjectMapper().writeValueAsString(this); } @Model(adaptables = { Resource.class }, defaultInjectionStrategy = DefaultInjectionStrategy.OPTIONAL) interface ProofPointsList { @Inject String getProofText(); @Inject String getProofIcon(); } }
HTL中直接调用该方法即可,这里context='unsafe'是因为已经是合法的JSON字符串,不需要HTL二次转义:
<sly data-sly-use.proofPoints="你的包名.ProofPointsModel"> <script type="application/json" id="proofPointsData"> ${proofPoints.serializedJson @ context='unsafe'} </script> </sly>
注意事项
- 两种方案都不需要发起额外的HTTP请求,所有数据都是组件渲染时在服务端直接生成
- 无特殊自定义需求优先选方案1,实现成本最低,和Sling Exporter的输出结果完全对齐
内容的提问来源于stack exchange,提问作者Archit Arora
相关产品推荐
相关产品推荐

