Reputation: 387
I have dictionary like this
mydict['student'] = {'name':'john', 'age':'36'}
IN my template i have the list of students like this
{{ object.students}}
I am displaying the list of students in the table like this
<table>
{% for student in object.students %}
<tr><td>{{student.name}}</td>
{% endfor%}
I have the complex scenario and i have to match the student name and age or whatever keys are in mydict
and if that matches only then show the student row otherwise no
Like this
if mydict.student.name == student.name && mydict.student.age == student.age
then show the row
The thing is i can have the variable number of keys in dictoanry so basically i am looking for something like filter
or whatever
to which i pass the dictionary
and object and it return me either true or false. something like
if getResult(mydict['student'], student)
def getResut(a,b):
result_list =[]
for key in a:
if b[key] icontains a[key]:
result_list.append(True)
else
return False or result_list.append(False)
It will return me the list of true or Flase as list . Then i will check if all are true then it will return True othwise it will return False
I have to do all that in either template
or filters
Upvotes: 0
Views: 508
Reputation: 39669
You need to write custom filter:
@register.filter(name='show_student')
def show_student(obj, d):
show = True
for key, val in d.iteritems():
if hasattr(obj, key):
obj_val = getattr(key, obj)
if obj_val != val:
show = False
break
else:
show = False
break
return show
Then in template you can do:
{% if student|show_student:my_dict %}
# show student
{% endif %}
P.S: you have to be careful that the dictionary should contains attribute values of same type e.g. 'age':'36' in this age is a string, usually it should be an integer value
Upvotes: 2