1

I'm sorting a dictionary like this:

{% for s in selected.values() | sort(attribute="last_name") | sort(attribute="first_name") | sort(attribute="middle_initial") %}

But sometimes the input dictionary doesn't contain last_name, how could I go about sorting the dictionary in the event the key isn't present? I'd like to use a default value similar to how you would access a dictionary in Python3 as such:

selected.get('last_name', 'Unknown')
TomNash
  • 3,147
  • 2
  • 21
  • 57
  • Possible duplicate of [Stable sorting in Jinja2](https://stackoverflow.com/questions/16143053/stable-sorting-in-jinja2) – Kostas Charitidis Oct 24 '19 at 12:25
  • Just to highlight what's discussed in Kostas' dupe link: Jinja2's `sort` filter **does not** support chaining to sort by multiple levels. So your code, even if it didn't fail on missing `last_name`s, would only effectively sort on `middle_initial` (the last one). – Jeronimo Oct 24 '19 at 13:21

1 Answers1

0

If I'm not mistaken, you can check that a variables exist with

{% if my_variable %}
   do something
{% end if%}

So perhaps you can check if an attribute exists with

{% if object_list.attribute %}
   do something
{% end if%}
anowlinorbit
  • 347
  • 1
  • 2
  • 10