Breaking out of a for loop from a nested if statement in Django -
is there way break out of for loop inside if statement. our database incorrectly storing multiple primary phones , break out of loop after first primary phone found. thank in advance help.
{% phone in user_phones %} {% if phone.primary %} <div>{% if phone.type %}{{ phone.type|title }}: {% endif %}<span itemprop="telephone">{{ phone.phone_format }}</span></div> {% endif %} {% endfor %} updated:
or fail if condition creating variable within if true branch
if have stay within template layer use regroup.
{% regroup user_phones|dictsort:"primary" primary phones_list %} {% phone in phones_list %} {% if phone.grouper %} {{ phone.list.0.type }} {% endif %} {% endfor %} what does
regroup dictsort filter (which works on querysets) groups instances in user_phones value of primary.
regroup add attribute named grouper, when grouping bool (the value of primary) either true or false.
for iterates on variable phones_list, provided regroup. since have sorted results primary, {% if phone.grouper %} tell when hit group of items primary == true.
regroup packs items belong group attribute list. first item can accessed phone.list.0.type, phone.list.0.phone_format, etc.
note:
if need access foo.list.0 many times can assigned variable (using with):
{% regroup user_phones|dictsort:"primary" primary phones_list %} {% items in phones_list %} {% if items.grouper %} {% items.list.0 phone %} <div>{% if phone.type %}{{ phone.type|title }}: {% endif %}<span itemprop="telephone">{{ phone.phone_format }}</span></div> {% endwith %} {% endif %} {% endfor %}
Comments
Post a Comment