oTree Forum >

Looping over dicts in template

#1 by Hauke


I created some sort of a nested dict, that O pass to the template using vars_for_template. Within the template, I would like to loop over these items to eventually create a twitter-ish feed. Unfortunately, it doesn't work too well. I am sure the answer is quite obvious but I don't see it...

So here is my Page:

class Results(Page):
    def vars_for_template(player: Player):
        tweets = {'1':
                      {'handle': '@elhotzo',
                       'name': 'El Hotzo',
                       'date': '9. Nov.',
                       'text': 'Some Text A',
                       'replies': 9,
                       'retweets': 17,
                       'likes': 9
                      {'handle': '@aurelmertz',
                       'name': 'Aurel',
                       'date': '10. Nov.',
                       'text': 'Some Text B',
                       'replies': 4,
                       'retweets': 7,
                       'likes': 124
                      {'handle': '@aurelmertz',
                       'name': 'Aurel',
                       'date': '10. Nov.',
                       'text': 'Some Text C',
                       'replies': 17,
                       'retweets': 24,
                       'likes': 532
        return dict(
The corresponding template:

            {{ for i in tweets }}
                <div class="card mb-5">
                    <div class="card-body">
                        <h5 class="card-title"></h5>
                        <h6 class="card-subtitle mb-2 text-muted">{{i.handle}} &middot; {{i.date}}</h6>
                        <p class="card-text">

                        <i class="bi bi-chat text-secondary">&nbsp;{{i.replies}}&emsp;</i>
                        <i class="bi bi-arrow-repeat text-secondary">&nbsp;{{i.retweets}}&emsp;</i>
                        <i class="bi bi-heart text-secondary">&nbsp;{{i.likes}}&emsp;</i>

           {{ endfor }}
Thanks a lot in advance!

#2 by Chris_oTree

In Python, looping over a dict just gives you the keys, not the values. So the above code just yields '1', '2', '3'. Instead you should loop over tweets.items() or tweets.values().

#3 by Hauke

Thanks once again for the very fast response! That works.

Write a reply

Set forum username