Sorting dict in jinja

871 views
Skip to first unread message

Ari Maniatis

unread,
Sep 24, 2015, 12:19:52 AM9/24/15
to Salt-users
I imagine many people have a template file in jinja that looks a bit like this:

{% for id, site in salt['pillar.get']('haproxy:sites').items() %}

Now I'm finding that changes to the pillar will sometimes cause a larger than necessary diff. That takes more time to verify and mistakes can happen because its harder to verify the output.

So I'd like to sort the dict in the for loop. I don't care too much what I sort by; perhaps the id or even an attribute in the site object. Now I don't really need a dict and could do with just a simple list rooted in the id, but that's what salt is giving me.

Is there a good way to do this?


Cheers
Ari

Florian Ermisch

unread,
Sep 24, 2015, 1:22:51 AM9/24/15
to salt-...@googlegroups.com
Hi Ari,

I think running the keys through a jinja filter would be the easiest option:

{% set sites = salt['pillar.get']('haproxy:sites', {}).items() %}
{% for id in sites|sort %}
whatever {{ sites[id] }}
[…]


Regards, Florian

Onno

unread,
Sep 24, 2015, 4:22:13 AM9/24/15
to salt-...@googlegroups.com
Hi Ari,

Or maybe;

{% for accu_key, accu_value in accumulator | dictsort -%}
{% for text in accumulator[accu_key] -%}
{{ text }}
{% endfor -%}
{% endfor -%}

Regards,
Onno


Florian Ermisch schreef op 2015-09-24 07:22:
Reply all
Reply to author
Forward
0 new messages