首页 > 解决方案 > django {% url %} 模板循环

问题描述

我的 url.py

app_name="application_name"
urlpatterns=[
    url(r"^staff/",include('application_name.staff_url', namespace='staff')),
    url(r"^customer/",include('application_name.customer_url', namespace='customer')),
]

员工网址.py

from application_name import views
app_name="staff"
urlpatterns=[
    url(r"^customers/",views.customers, name='customers'),
    url(r"^orders/$", views.orders, name='orders'),
    url(r"^payments/$", views.payments, name='payments'),
]

customer_url.py

from application_name import views
app_name="customer"
urlpatterns=[
    url(r"^items/",views.items, name='items'),
    url(r"^checkout/$", views.checkout, name='checkout'),
    url(r"^make_payment/$", views.make_payment, name='make_payment'),
]

员工网址将是staff/ordersstaff/payments客户网址将是customer/itemscustomer/checkout

在我的视图文件中,我已将每个链接放在一个列表中,该列表将在模板中迭代并将其放置在会话中

这是我的观点.py

staffLink=[
    {'linkfield':"customers", 'name':"Customers",'slug':"staff"},
    {'linkfield':"orders", 'name':"Orders",'slug':"staff"},
    {'linkfield':"payments", 'name':"payments",'slug':"staff"}]
                    
links=staffLink
request.session['links']= links
request.session['sub']= 'staff'

context_dict = {'links':links} 
                

这是我的html模板

{% for link in request.session.links %}
    {% if request.session.sub =="staff" %}
        <a href="{% url  'application_name:staff' link.linkfield as the_url %}" class="nav-link">
    {% elif request.session.sub =="customer" %}
        <a href="{% url  'application_name:customer' link.linkfield as the_url %}" class="nav-link">
    {% endif %}
{% endfor %}

PL

这是以下结果

  1. 当我包含 if 语句时,即{% if request.session.sub =="staff" %}。产生以下错误

    django.template.exceptions.TemplateSyntaxError:无法解析剩余部分:来自 '=="staff"' 的 '=="staff"'

  2. 当我排除 if 语句时,我这样做只是<a href="{% url 'application_name:staff' link.linkfield as the_url %}" class="nav-link"> 为了测试目的。我收到以下错误

    django.urls.exceptions.NoReverseMatch:找不到“员工”的反向。'staff' 不是有效的视图函数或模式名称。

请问我该怎么做才能让if语句与anchor语句一起工作

标签: pythondjangodjango-models

解决方案


==你应该在和"staff"字符串之间写一个空格,所以:

{% if request.session.sub == "staff" %}
    …
{% endif %}

至于 URL,您不会引用一个 URL,include(…)因为它是 URL 的集合。例如:

<a href="{% url 'staff:customers' link.linkfield as the_url %}" class="nav-link">

推荐阅读