django - 将变量共享到 django 中包含的模板
问题描述
在对象被传递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 文件中,以使事情井井有条。我可以通过引用模态 html 文件来做到这一点,include
如下所示:
{% 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 %}
推荐阅读
- c - 为什么不能在 C 中比较结构的 NULL 性?
- android - Android BLE:onCharacteristicRead 仅在第一次工作
- python-3.x - aiodocker async creation of the container
- amazon-web-services - 我可以使用 VPC 端点从我的账户 ec2 连接到不同的账户 AWS 服务(s3、dynamoDb)吗?
- asp.net-core - 如何在 asp.net core 2.0 (iis) 中重定向 301,添加谷歌分析代码
- python - AppJar 线程允许 GUI 更新
- excel - 如何根据excel中的用户选择禁用复选框
- python - Pandas - 合并包含一些空值的列
- ruby-on-rails - Rails 将日志数据保存到数据库
- amazon-web-services - update 命令中的临时块使 DISK FULL 红移