I am trying to get a nested list of dictionaries values printed to a single line using Jinja. I'm able to get them across multiple lines but I'm not sure how to get all values on a single line.
This is my example data Structure, trimmed for briefness
"interfaces": [
{
"display": "Ge1/0/1",
"enabled": true,
"id": 325,
"ip_addresses": [],
"label": "",
"lag": null,
"last_updated": "2022-05-12T22:42:29.740411Z",
"link_peer": null,
"link_peer_type": null,
"mac_address": null,
"mark_connected": false,
"mgmt_only": false,
"mode": {
"label": "Tagged",
"value": "tagged"
},
"mtu": null,
"name": "Ge1/0/1",
"parent": null,
"rf_channel": null,
"rf_channel_frequency": null,
"rf_channel_width": null,
"rf_role": null,
"tagged_vlans": [
{
"display": "Data (10)",
"id": 1,
"name": "Data",
"url": "http://10.10.0.144:8000/api/ipam/vlans/1/",
"vid": 10
},
{
"display": "VoIP (11)",
"id": 3,
"name": "VoIP",
"url": "http://10.10.0.144:8000/api/ipam/vlans/3/",
"vid": 11
},
{
"display": "MGMT (20)",
"id": 4,
"name": "MGMT",
"url": "http://10.10.0.144:8000/api/ipam/vlans/4/",
"vid": 20
}
],
This is my current Jinja2 code:
{% for interface in interfaces %}
interface {{ interface.display }}
{% for vlan in interface['tagged_vlans'] %}
untagged {{ vlan.vid }}
{% endfor %}
{% endfor %}
Which gives as my current output
interface Ge1/0/1
untagged 10
untagged 11
untagged 20
This is my expected output
interface Ge1/0/1
untagged 10,11,20
You don't need to loop here. It's much easier to join the values. In a nutshell:
{% for interface in interfaces %}
interface {{ interface.display }}
untagged {{ interface.tagged_vlans | map(attribute='vid') | join(',') }}
{% endfor %}
Meanwhile, if you ever need to loop and remove some white spaces/new lines from the output, see jinja2 whitespace control