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'srangeis left-inclusive and right-exclusive. So ifsegmentsLengthis 3, this loop will only run for 1 and 2—you'll miss the last segment. You need to adjust it torange(1, segmentsLength + 1)to cover all indices. - The bigger issue is the path
file.value['segments'].value[sg]. Iffile.value['segments']is already the Map containing your segment entries, you don't need that extra.valuelayer. Plus, if the keys in yoursegmentsMap are string-type numbers (like "1", "2" instead of numeric 1, 2), using a numeric indexsgwon'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

