{% url ... %} Django 中的模板标签包含模板看不到变量

{% url ... %} templatetag in Django included template not seeing variable

我在包含的模板中遇到我无法理解的奇怪行为。

urls.py

urlpatterns = (
    path(
        "items/",
        views.list_view,
        name="list-view",
    ),
    path(
        "item/<int:pk>/",
        views.detail_view,
        name="detail-view",
    ),
)

views.py

def list_view(request):
    items = Item.objects.all()
    return render(request, "parent_template.html", context={"items": items})

def detail_view(request, pk):
    item = get_object_or_404(Item, pk=pk)
    return render(request, "detail_template.html", context={"item": item} 

parent_template.html

{% for item in items %}
  Parent: {{ item.pk }}
  {% include 'child_template.html' %}
{% endfor %}

child_template.html

Child: {{ item.pk }}
URL: {% url 'detail-view' item.pk %}

我收到反向错误:

Reverse for '/test/url/<int:pk>/' with arguments '('',)' not found. 1 pattern(s) tried: ['test/url/(?P<pk>[0-9]+)/\Z']

如果我删除 {% url ... %} 模板标签,它会正确呈现并显示:

Parent: 1 Child: 1

很明显项目在上下文中,但由于某种原因它没有被传递到模板标签。

我也尝试过类似的变体:

{% for item in items %}
    {% with new_item=item %}
        {% include 'child_template.html' %}
    {% endwith %}
{% endfor %}

有什么想法吗?

我正在使用 Django 3.2.12

我刚刚发现错误 - 我找错了地方。我的完整代码如下所示:

parent.html

<!-- {% include 'child_template.html' %} -->

{% for item in items %}
    {% with new_item=item %}
        {% include 'child_template.html' %}
    {% endwith %}
{% endfor %}

我没有注意模板顶部的 HTML 注释。显然 Django 仍在服务器端呈现代码,此时在其上下文中没有项目。