简体   繁体   中英

Django iterate on template with 2 dicts from views.py

I have the following code :

views.py file :

twittdict = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6}
twitlistdict = {'A' : 'a', 'B': 'b', 'C': 'c'}
return render(request, 'homepageapp/home.html', {'twittdict' : twittdict, 
'twitlistdict' : twitlistdict})

homepage.html file :

{% for user in twitlistdict %}
                          <a 
href="https:*/{{ twittdict.user.3 }}"> 
<div class="card border-white mb-3">
                   <p class="card-title"><div class="media">
            <img class="mr-3 align-self-center" 
src="https://source.unsplash.com/random/90x94">
            <div class="media-body">
                <h5>{{ twittdict.user.0 }}</h5>
                <h6>@{{ twittdict.user.1 }}</h6>
                <p></p>
            </div>
        </div></p>
                    <img class="card-img-top img-fluid" 
src="https://source.unsplash.com/random/301x200" alt="">
                    <div class="card-body">
                        <p class="card-text">{{ twittdict.user.4 }}</p>
                        <p class="card-text">
                           <hr>
                            <i class="fas fa-retweet">{{ twittdict.user.6 }} 
</i> <i class="far fa-heart">{{ twittdict.user.5 }}</i> <span class="pl-5"> 
{{ twittdict.user.2 }}</span>
                        </p>
                    </div>
                </div>
                      </div>{% endfor %}

When i preview the page with the browser, instead of loop items ( eg: twittdict.user.2 corresponding value ), nothing is showed. Blank. How can i made this work and display correct values in the page ? Really struggling with this. Any help is greatly appreciated Thank you in advance.

The keys in your twitlistdict (eg 'A', 'B') do not correspond to any keys in twittdict (eg '0', '1').

Also you can not get a variable index in the template by using twittdict.user , it will try to get twittdict['user'] . Accessing by numeric keys will only work with lists, not with dictionaries.

Try to form one dictionary in python instead of two, that will make working with it easier in the template. A useful thing might be to use dict.items() to get both the key and the value of a dict item:

{% for key, value in my_dict.items() %} 
  {{ key }}: {{ value }} 
{% 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