简体   繁体   中英

How do I use a complex context with Django?

I'm learning Django by building simple contact manager,
I use Django 1.7.3 with Python 2.7.
I'm confused about how to render the template with the given context.

context = {
    'name': 'John Doe',
    'age': 24,
    'email_ids' : [
        {
            'use': 'personal',
            'email': 'johndoe@example.com' 
        },
        {
            'use': 'work',
            'email': 'manager@example.com'
        },
        {
            'use': 'spam',
            'email': 'iwantyournewsletter@example.com'
        }
    ]
    'phones': [
        {
            'use': 'personal',
            'number': '+1234567890'
        },
        {
            'use': 'work',
            'number': '+1234567891'
        }
    ]
}

My template block is,

{% block  address_slot %}
    Name : {{ name }}
    Age : {{ age }}
    Email Address:
        {{ use }} : {{ email }}
    Phone Number: 
        {{ use}}  : {{ number }}
{% endblock %}

I'm not sure how to insert the dict (email details and the number details) inside the list ( email_ids and phones ) in the context, While I got the name and age inserted.

In python I use

for email in context['email_ids']:
    print(email['email_ids'])

To print the emails while what is the equivalent in Django templates?

How can I insert the email address in the related field?

Use the {% for %} template tag and dot notation to look up keys in each dictionary, EG:

{% for email_id in email_ids %}
  Email Address:
    {{ email_id.use }} : {{ email_id.email }}
{% endfor %}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM