在views.py
中,thing
对象被传递给index.html
。
def index(request):
return render(request, "myapp/index.html", {
'things': Thing.objects.all()
})
index.html
设置如下:
{% block body %}
{% for thing in things %}
{{ thing.attribute }}
<button type="button" class="btn" data-toggle="modal" data-target="#exampleModal"></button>
{% endfor %}
{% endblock %}
我想将呈现按钮引用的模态的html分离到另一个html文件中,以保持事物的有序性。我可以通过引用带有include
的模式html文件来做到这一点,如下所示:
{% block modal_code %}
{% include 'myapp/modal_code.html' with things=things %}
{% endblock %}
当我尝试共享things
对象时,当我这样使用它时,它没有被合并到modal_code.html
中:
{% for thing in things %}
{{ thing.attribute }}
{% endfor %}
从文档中,您可以传递类似以下的上下文
{% include "name_snippet.html" with person="Jane" greeting="Hello" %}
所以在你的情况下:
{% block modal_code %}
{% include 'myapp/modal_code.html' with things=things %}
{% endblock %}