python - 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/orders
或staff/payments
客户网址将是customer/items
或customer/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
这是以下结果
当我包含 if 语句时,即
{% if request.session.sub =="staff" %}
。产生以下错误django.template.exceptions.TemplateSyntaxError:无法解析剩余部分:来自 '=="staff"' 的 '=="staff"'
当我排除 if 语句时,我这样做只是
<a href="{% url 'application_name:staff' link.linkfield as the_url %}" class="nav-link">
为了测试目的。我收到以下错误django.urls.exceptions.NoReverseMatch:找不到“员工”的反向。'staff' 不是有效的视图函数或模式名称。
请问我该怎么做才能让if语句与anchor语句一起工作
解决方案
==
你应该在和"staff"
字符串之间写一个空格,所以:
{% if request.session.sub == "staff" %}
…
{% endif %}
至于 URL,您不会引用一个 URL,include(…)
因为它是 URL 的集合。例如:
<a href="{% url 'staff:customers' link.linkfield as the_url %}" class="nav-link">
推荐阅读
- typescript - Typescript 可以推断具体实例中的映射类型,但不能推断泛型类型
- python - Python:带有 MATLAB 函数的 .p 文件
- python - Python数据帧转置时间序列(行到列)
- reactjs - 从firebase实时数据库获取数据到react redux时出现问题
- angular - ERROR 错误:未捕获(在承诺中):错误:无法匹配任何路由。有什么想法可以解决这个问题吗?
- python - 我想从 json 文件中提取特定部分到 python 列表
- flutter-layout - DraggableScrollableSheet 子项从工作表的中间开始颤动
- flutter - 如何处理彼此添加空值
- docker-compose - docker-compose 多个 postgres 数据库
- python - 如何将 Sublime Text 中的数据框显示到控制台中以更好地探索它?