You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在AEM的HTL中渲染Sling Model生成的JSON输出?

在AEM的HTL中渲染Sling Model的JSON输出

问题描述

已基于Sling Models创建AEM自定义组件Mycomponent,并实现getJson()方法将Model序列化为JSON字符串,希望在mycomponent.html中调用该方法,把JSON输出渲染到页面中。

解决方案

方法1:直接调用getJson()方法

在HTL文件中通过data-sly-use注入Sling Model,调用其getJson()方法输出。由于HTL默认会转义HTML特殊字符,需指定@ context='unsafe'确保JSON字符串原样输出:

<!-- mycomponent.html -->
<sly data-sly-use.model="com.yourpackage.Mycomponent"></sly>

<!-- 以纯文本形式展示JSON -->
<pre>${model.json @ context='unsafe'}</pre>

<!-- 作为JavaScript变量供前端使用 -->
<script>
  const componentData = ${model.json @ context='unsafe'};
  console.log(componentData);
</script>

方法2:使用Sling Model Exporter(更推荐)

你的Model已配置@Exporter注解,这是AEM官方推荐的序列化方式,无需手动实现getJson(),还能保证序列化配置一致性。

步骤1:移除手动实现的getJson()方法

删除Model中的getJson()方法,避免重复逻辑和配置不一致问题。

步骤2:在HTL中引用Exporter生成的JSON

通过组件路径+选择器+扩展名的方式获取JSON,示例如下:

<!-- 方式1:通过fetch请求获取JSON并处理 -->
<script>
  fetch('${resource.path}.karthik.json')
    .then(response => response.json())
    .then(data => {
      console.log(data);
      // 执行前端业务逻辑
    });
</script>

<!-- 方式2:直接嵌入JSON内容 -->
<sly data-sly-resource="${resource.path @ selectors='karthik', extension='json'}"></sly>

<!-- 方式3:用pre标签展示格式化后的JSON -->
<pre data-sly-include="${resource.path @ selectors='karthik', extension='json'}"></pre>

优化建议

  1. 避免手动创建ObjectMapper:若坚持使用getJson()方法,不要每次调用都new ObjectMapper(),应通过@Inject注入AEM提供的ObjectMapper实例,保证配置一致性和性能:
@Inject
private ObjectMapper objectMapper;

public String getJson() {
    String str = "";
    try {
        // 启用WRAP_ROOT_VALUE,与@Exporter配置保持一致
        objectMapper.enable(SerializationFeature.WRAP_ROOT_VALUE);
        str = objectMapper.writeValueAsString(this);
        logger.info("Serialized JSON: {}", str);
    } catch (JsonProcessingException e) {
        logger.error("Error serializing Mycomponent: {}", e.getMessage());
    }
    return str;
}
  1. 保持序列化配置一致:手动实现的getJson()需与@Exporter的配置对齐(如WRAP_ROOT_VALUE),否则输出的JSON结构会和Exporter生成的不一致。

内容的提问来源于stack exchange,提问作者Karthikeya Reddy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 08:30:12