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

Pebble模板通过键获取Map元素失败,求有序生成XML方案

Hey there! Let's break down what's going wrong with your Pebble template and fix that segment access issue.

First, let's unpack why your first approach isn't working:

  • When you use range(1, segmentsLength), remember that Pebble's range is left-inclusive and right-exclusive. So if segmentsLength is 3, this loop will only run for 1 and 2—you'll miss the last segment. You need to adjust it to range(1, segmentsLength + 1) to cover all indices.
  • The bigger issue is the path file.value['segments'].value[sg]. If file.value['segments'] is already the Map containing your segment entries, you don't need that extra .value layer. Plus, if the keys in your segments Map are string-type numbers (like "1", "2" instead of numeric 1, 2), using a numeric index sg won't match the keys—you need to convert it to a string first.

Here's a fixed version of your first approach that addresses these problems:

{% set segments = file.value['segments'] %}
{% set segmentsLength = segments|length %} 
{% for sg in range(1, segmentsLength + 1) %}
    {% set segment = segments[str(sg)] %}
    <Segment type="{{ segment.value['segmentType'] }}">
        <Start>{{ segment.value['start'] }}</Start>
        <End>{{ segment.value['end'] }}</End>
    </Segment>
{% endfor %}

If your segments is actually a list (not a Map) and you just need to skip the first element while keeping the correct order, a simpler fix is using the slice filter instead of manually handling ranges:

{% for segment in file.value['segments']|slice(start=1) %}
    <Segment type="{{ segment.value['segmentType'] }}">
        <Start>{{ segment.value['start'] }}</Start>
        <End>{{ segment.value['end'] }}</End>
    </Segment>
{% endfor %}

And if the issue is that your segments Map isn't iterating in the order you need, you can sort the Map entries by their keys first:

{% set sortedSegments = file.value['segments']|sort(attribute='key') %}
{% for segmentEntry in sortedSegments %}
    {% set segment = segmentEntry.value %}
    <Segment type="{{ segment.value['segmentType'] }}">
        <Start>{{ segment.value['start'] }}</Start>
        <End>{{ segment.value['end'] }}</End>
    </Segment>
{% endfor %}

The core here is figuring out whether segments is a list or a Map—your second loop works because Pebble can iterate over both, but accessing them by index vs. key requires different syntax.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 06:50:52