在我正在处理的项目中,默认情况下我需要select
标记位于特定的option
。我试图让它做到这一点,如果我将变量设置为某个数字,页面加载时将选择相应的选项。出于某种原因,我用来判断该选项是否与变量相同的代码总是返回false。
View.py
@login_required
def display_work(request, id, chapter = 1):
info = dict()
work = Work.objects.get(id = id)
chapters = Chapter.objects.filter(work = id).order_by("order_number")
info['title'] = work.title
info['summery'] = work.summery
info['current_chapter'] = chapter # the number the options are compared to
print chapter
info['id'] = id
num_chapters = 0
chapter_list = []
for c in chapters:
temp = (c.title, c.order_number) # where the numbering for the options is set (see template code)
chapter_list.append(temp)
num_chapters += 1
info['total_chapter'] = num_chapters
content = chapters[int(chapter)-1].content
return render_to_response("SubMain/display_work.html", {'STATIC_URL':STATIC_URL, "info":info, "chapters": chapter_list, "content": content})
模板:模板在列表中运行,检查其创建的选项是否是当前章节。如果是这样,它应该“选择”它。
{% for t, o in chapters %}
<option value="/work/{{ info.id }}/{{ o }}" {% if o == info.current_chapter %} selected="selected" {% endif %}>Chapter {{ o }}: {{ t }}</option>
{% endfor %}
然而,每当我运行代码时,都没有被选中(if标签中有什么)。通过我已完成的调试,我确认o
为2,info.current_chapter
为2。
答案 0 :(得分:1)
在模板中尝试使用单个'='操作而不是'=='。
<option value="/work/{{ info.id }}/{{ o }}" {% if o = info.current_chapter %} selected="selected" {% endif %}>Chapter {{ o }}: {{ t }}</option>
答案 1 :(得分:1)
尝试ifequal
{% for t, o in chapters %}
<option value="/work/{{ info.id }}/{{ o }}" {% ifequal o info.current_chapter %} selected="selected" {% endifequal %}>Chapter {{ o }}: {{ t }}</option>
{% endfor %}