JSON自适应卡片容器迭代场景下$when条件使用问题咨询
问题原因及正确配置方式
你原本的$when写法本身符合官方规范,不生效通常是以下两个常见原因导致:
- 未使用自适应卡片模板SDK完成数据绑定:
$data、$when这类模板语法不属于标准自适应卡片的原生渲染能力,必须先调用模板SDK将模板JSON和数据集合并为最终的普通自适应卡片JSON,再交给渲染器渲染,不能直接把模板JSON传入普通渲染器。 - 部分旧版本模板SDK对同级元素的
$when支持存在缺陷:可以将每个动态渲染的输入控件外层包裹独立Container,将$when写在Container属性上即可兼容。
修正后的模板示例
{ "type": "Container", "$data": "${attributeData.data}", "spacing": "medium", "items": [ { "type": "TextBlock", "weight": "Bolder", "text": "${fieldName}", "wrap": true }, { "type": "Container", "$when": "${fieldType == 1}", "items": [ { "type": "Input.Text", "id": "${fieldId}", "placeholder": "Add a comment", "isMultiline": true, "value": "${fieldValue}" } ] }, { "type": "Container", "$when": "${fieldType == 2}", "items": [ { "type": "Input.Date", "id": "${fieldId}", "value": "${fieldValue}" } ] }, // 补充fieldType=0对应的数字输入控件示例 { "type": "Container", "$when": "${fieldType == 0}", "items": [ { "type": "Input.Number", "id": "${fieldId}", "value": "${$toNumber(fieldValue)}" } ] } ] }
替代实现方案
如果$when始终无法适配你的渲染环境,可以采用条件过滤的方案:针对每种控件类型单独做一次遍历渲染,注意该方案会将同类型字段聚合展示,会改变原始字段的顺序:
{ "type": "Container", "spacing": "medium", "items": [ // 渲染所有文本类型字段 { "type": "Container", "$data": "${filter(attributeData.data, x => x.fieldType == 1)}", "items": [ { "type": "TextBlock", "weight": "Bolder", "text": "${fieldName}", "wrap": true }, { "type": "Input.Text", "id": "${fieldId}", "placeholder": "Add a comment", "isMultiline": true, "value": "${fieldValue}" } ] }, // 渲染所有日期类型字段 { "type": "Container", "$data": "${filter(attributeData.data, x => x.fieldType == 2)}", "items": [ { "type": "TextBlock", "weight": "Bolder", "text": "${fieldName}", "wrap": true }, { "type": "Input.Date", "id": "${fieldId}", "value": "${fieldValue}" } ] } ] }
内容的提问来源于stack exchange,提问作者Gooyou
相关产品推荐
相关产品推荐

