首页 > 解决方案 > 将变量共享到 django 中包含的模板

问题描述

在对象被传递views.py给.thingindex.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 %}

标签: django

解决方案


从文档中,您可以像这样传递上下文

{% include "name_snippet.html" with person="Jane" greeting="Hello" %}

所以在你的情况下:

{% block modal_code %}                    
    {% include 'myapp/modal_code.html' with things=things %}
{% endblock %}

推荐阅读