You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Django模板中同时遍历选项与字母列表变量

可行的实现方案

方案1:模板内直接生成选项字母(无需依赖传入的letters列表)

不用修改视图,直接利用ASCII码转换生成字母。A的ASCII码是65,结合循环的索引值(从0开始)就能自动生成对应字母,选项超过5个时还能自动扩展F、G等:

{% if question_list %}
  <ul>
  {% for question in question_list %}
    <li><a href="#">{{question.question}}</a></li>
      <ul>
        {% for choice in question.choice_set.all %}
        <li>{{ 65|add:forloop.counter0|chr }}. {{ choice.text }}</li>
        {% endfor %}
      </ul>
  {% endfor %}
  </ul>
{% else %}
  <p>No questions available</p>
{% endif %} 

方案2:视图层预处理选项与字母的配对

如果一定要用你定义的letters列表,可以在视图中为每个问题提前把字母和选项配对好,模板直接遍历即可:
修改views.py代码:

def choice(request):
    question_list = get_list_or_404(Question)
    page = get_object_or_404(Page, name='about')
    letters = ["A", "B", "C", "D", "E"]
    # 为每个问题生成带字母的选项组合
    for question in question_list:
        # 只取和选项数量匹配的字母,避免索引越界
        question.paired_choices = list(zip(letters, question.choice_set.all()))
    return render(request,
                  'qview/choice.html',
                  {
                    'question_list': question_list,
                    'page': page,
                   }
                  )

对应修改模板:

{% if question_list %}
  <ul>
  {% for question in question_list %}
    <li><a href="#">{{question.question}}</a></li>
      <ul>
        {% for letter, choice in question.paired_choices %}
        <li>{{ letter }}. {{ choice.text }}</li>
        {% endfor %}
      </ul>
  {% endfor %}
  </ul>
{% else %}
  <p>No questions available</p>
{% endif %} 

方案3:自定义模板过滤器(适合多场景复用)

如果多个页面都需要给选项加字母标识,可以写一个可复用的模板过滤器:

  1. 在你的app目录下创建templatetags文件夹,新建quiz_tags.py文件:
from django import template

register = template.Library()

@register.filter
def get_option_letter(index, letters=["A", "B", "C", "D", "E"]):
    # 索引超出字母列表长度时,自动生成后续字母
    return letters[index] if index < len(letters) else chr(65 + index)
  1. 在模板顶部加载过滤器:
{% load quiz_tags %}
  1. 循环中使用过滤器:
{% if question_list %}
  <ul>
  {% for question in question_list %}
    <li><a href="#">{{question.question}}</a></li>
      <ul>
        {% for choice in question.choice_set.all %}
        <li>{{ forloop.counter0|get_option_letter }}. {{ choice.text }}</li>
        {% endfor %}
      </ul>
  {% endfor %}
  </ul>
{% else %}
  <p>No questions available</p>
{% endif %} 

内容的提问来源于stack exchange,提问作者Iggy Comdore

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 15:00:45