Django:在模板中分配变量

Hel*_*nar 50 django django-templates

如何在django模板系统中分配变量?

假设Restaurant是一个模型:

{% restaurant_id as restaurant.id %}或者{{ restaurant_id as restaurant.id }}不工作.

Lau*_*Mat 80

您可以使用with template标签,并分配一个内部模板变量,如下所示:

{% with restaurant_id=restaurant.id %}
... use restaurant_id in this template section ...
{% endwith %}
Run Code Online (Sandbox Code Playgroud)


小智 18

注意:您可以在"with"模板标记中使用过滤器:

foo is {{ foo }}
{% with bar=foo|slice'6:9' %}
  bar is {{ bar }}
{% endwith %}
Run Code Online (Sandbox Code Playgroud)