在django模板中嵌套for循环未显示正确的输出

时间:2017-06-28 13:13:31

标签: django for-loop jinja2 nested-loops

所以当我在 views.py 文件中打印它时,我有这个循环显示正确的输出

for x in list4:
        print x[0]
        for y in x[3]:
            print y[1]
        print "\n"

输出:

test question edited
test1
test2
test3


test question
hello
hello12
hkjhjkh
hjk
hkjhkj


another test
sdfsdf
sdfsdf


test2
sdfsd
sdfsd


another
sdfsdf
fsdfsd
sdf
sdfsd
fsd

但是在django模板中运行相同的循环以显示表单中的值时它会显示重复的输出

test.jinja2代码

{% extends "base.jinja2" %}
{% block content %}
{% block body %}





        {% for x in ques %}
            <form class='form-horizontal' method=POST action="/test-portal/student/test/">
            <input type="hidden" name="csrfmiddlewaretoken" value="{{ csrf_token }}">






                        <div class="form-group">

                            <input type="hidden" name="id" value={{x.0}}>
                            <label for="ques_title" class="col-sm-2 control-label" name='ques_title'>{{x[0]}}</label>
                        </div>

                        {% for y in x[3] %}
                            <!-- {% for b in y %} -->

                                <div class="form-group">
                                    <div class="col-sm-2">
                                <!-- <input type='checkbox' name='flag' id="new" value={{x}}> -->
                                        <label for="option" class="col-sm-2 control-label" name='ques_title'>{{y[1]}}</label>
                                    </div>
                                </div>
                            <!-- {% endfor %} -->
                        {% endfor %}



        {% endfor %}
                    <div class="form-group">
                        <button type="submit" class="btn btn-default" name='button' value='submit'>SUBMIT</button>
                        <!-- <td><button type="submit" class="btn btn-default" name='button' value='options'>ADD OPTIONS</button></td> -->

                    </div>

            </form>



{% endblock %}
{% endblock %} 

模板的输出

test question edited
test1
test1
test1
test1
test2
test2
test2
test2
test3
test3
test3
test3

test question
hello
hello
hello
hello
hello12
hello12
hello12
hello12
hkjhjkh
hkjhjkh
hkjhjkh
hkjhjkh
hjk
hjk
hjk
hjk
hkjhkj
hkjhkj
hkjhkj
hkjhkj

another test
sdfsdf
sdfsdf
sdfsdf
sdfsdf
sdfsdf
sdfsdf
sdfsdf
sdfsdf

test2
sdfsd
sdfsd
sdfsd
sdfsd
sdfsd
sdfsd
sdfsd
sdfsd

another
sdfsdf
sdfsdf
sdfsdf
sdfsdf
fsdfsd
fsdfsd
fsdfsd
fsdfsd
sdf
sdf
sdf
sdf
sdfsd
sdfsd
sdfsd
sdfsd
fsd
fsd
fsd
fsd

1 个答案:

答案 0 :(得分:1)

正如@ alfonso.kim所述,问题是评论,因为django仍然认为评论的循环是一个实际循环所以删除

<!-- {% for b in y %} -->
<!-- {% endfor %} -->

代码工作正常。