在 Django 模板语言中包含标记——我可以向它传递什么?

Include tag in Django template language -- what can I pass in to it?

好的,所以可能有 "simple" 解决方案,但我是初学者,对我来说似乎没有什么简单的。

我有一个视图和一个模板,显示了我建模的汽车 class 实例的属性。这辆车 class 与我的自定义用户 class 存在多对多关系。显示给定 Car 实例属性的模板有很多变量。每辆汽车的视图工作正常。这是我无法开始工作的地方:

我为每个 User 实例都有一个用户配置文件页面。在该页面上,我想显示特定用户拥有的每辆汽车的属性 "favorited." 我不知道该怎么做。

我已经尝试使用 {% include %} 标签来包含 Car 模板的片段,然后使用 for 语句遍历用户最喜欢的集合。理论上,这将使用他们拥有的每辆汽车 "favorited" 填充用户页面并显示其属性。但是,我不知道如何将 {% include %} 标记传递给正确的上下文,以便为每个 Car 实例正确填充属性。这可能吗?

有没有我忽略的更简单的方法?

感谢任何帮助。谢谢!

使用 {% include ... with ... %} 语法:

{% for car in user.favorite_cars.all %}
    {% include "car.html" with name=car.name year=car.year %}
{% endfor %}

另一种选择是 {% with %} 标签:

{% for car in user.favorite_cars.all %}
    {% with name=car.name year=car.year %}
        {% with color=car.color %}
            {% include "car.html" %}
        {% endwith %}
    {% endwith %}
{% endfor %}

UPDATE:如果无法从 Car 模型获取模板数据,则必须使用 custom inclusion tag:

from django import template

register = template.Library()

@register.inclusion_tag('car.html')
def show_car(car):
    history = get_history_for_car(car)
    return {'name': car.name, 'history': history}

模板中的:

{% load my_car_tags %}

{% for car in user.favorite_cars.all %}
    {% show_car car %}
{% endfor %}