如何在Django页面提取字典键值对并展示作者名言?
解决作者与名言对应展示的问题
你的代码把作者和名言拆成两个独立列表传递给模板,这种方式不仅冗余,还容易在模板渲染时出现对应关系出错的问题(比如后续字典结构变动时)。更简洁可靠的方式是直接传递字典的键值对集合,让模板可以直接遍历每个作者与其对应的名言。
优化后的视图函数
quotes = { "Arthur Ashe": "Start where you are, Use what you have, Do what you can.", "Steve Jobs": "Don’t watch the clock; do what it does. Keep going.", "Sam Levenson": "Don’t watch the clock; do what it does. Keep going.", "Robert Collier": "Success is the sum of small efforts, repeated day in and day out.", # 去掉了开头多余的空格 "Nelson Mandela": "It always seems impossible until it’s done.", "Mahatma Gandhi": "The future depends on what you do today.", "Zig Ziglar": "You don’t have to be great to start, but you have to start to be great.", "Dave": "Discipline is doing what needs to be done, even if you don’t want to do it.", "Suzy Kassem": "Doubt kills more dreams than failure ever will.", "Pablo Picasso": "Action is the foundational key to all success." } def mypage(request): # 直接传递字典的键值对列表,每个元素是(作者, 名言)的元组 quote_items = list(quotes.items()) return render(request, "quotes/mypage.html", {"quote_items": quote_items})
对应的HTML模板示例(以Django模板语法为例)
{% for author, quote in quote_items %} <div class="quote-card"> <h3>{{ author }}</h3> <p>"{{ quote }}"</p> </div> {% endfor %}
额外提示
- 原字典中" Robert Collier"的作者名开头有多余空格,已经在优化代码中去掉,避免页面显示时出现不必要的缩进。
- 这种方式直接保持了作者与名言的对应关系,无需依赖列表索引,代码更易维护。
内容的提问来源于stack exchange,提问作者Dave
相关产品推荐
相关产品推荐

