chad
chad

Reputation: 707

Django Template Tag Loop dictionary variable

I've reading all the template tags posts regarding the loop variable in the key. Apparently Django does not support loop variable in key and I am not sure how to use the custom template tag.

I wanted to display something like this, but how can I achieve this with {% for i in mData %} loop ?

{{ mData.0.name }}
{{ mData.1.name }}
{{ mData.2.name }}

{{ mData.0.age }}
{{ mData.1.age }}
{{ mData.2.age }}

mData is a list of dictionaries.

mData = { "name":"alex", "age":"12"},{"name":"amy","age":"14"} ...

Upvotes: 1

Views: 759

Answers (4)

aliasav
aliasav

Reputation: 3168

Considering your data is in a list of dictionaries such as:

my_data = [{"name" : "abc" , "age":20,...}, {} , {}...]

You can access all attributes of each dictionary in your template this way:

{% for dict in my_data %}
<!-- Here dict would be each of the dictionary in my_data -->
<!-- You can access elements of dict using dot syntax, dict.property -->
   {{ dict.name }}, {{ dict.age }}, ... {{ dict.property }}
{% endfor %}

Reference links: Django templating language

If you want to structure your elements in the order you specifed, you can do something like this:

Name List:
{% for dict in my_data %}
my_data.name
{% endfor %}

Age List:
{% for dict in my_data %}
my_data.age
{% endfor %}

...
Prpoerty List:
{% for dict in my_data %}
my_data.property
{% endfor %}

Upvotes: 2

a134man
a134man

Reputation: 150

This solved the problem for me

{% for d in mData %}
{{ d.name }} {{ d.age }}
{% endfor %}

Upvotes: 1

TheGRS
TheGRS

Reputation: 133

Django template tags are intentionally very lightweight so that you don't put too much code into the template itself. If you need to do something complicated like loop over every other entry in the database, you should be setting that up in views.py instead of the template.

For the scenario you described, all you need to do is loop over the list of objects:

{% for data in datas %}
    {{ data.name }}
{% endfor %}
{% for data in datas %}
    {{ data.age }}
{% endfor %}

Upvotes: 1

Sinux
Sinux

Reputation: 1808

{% for k, v in mData.items %}
    {{ k }} {{ v }}

by the way, PEP8 suggest we name the variable as lower + _, but not hump like javascript or other languages.

Upvotes: -1

Related Questions