假设我有这些urlpatterns:
url(r'^area/(?P<area>[\w-]+)/?$', views.IndexView.as_view(), name="index"),
url(r'^$', views.IndexView.as_view(), name="index"),
如何使用模板标记url
来处理不带area
的可选if else
参数
我尝试了以下内容:
{% url 'index' area=area %}
问题是:
None
,则网址将变为/area/None
答案 0 :(得分:-2)
只用一个索引网址替换您的索引网址。
url(r'^(?:area/(?P<area>[\w-]+))?$', views.IndexView.as_view(), name="index")
我可以从shell
测试from django.core.urlresolvers import reverse, resolve
from django.template import Context, Template
Template("url1 is {% url 'index' %}").render(Context())
Template("url2 is {% url 'index' area=1 %}").render(Context())
Template("url3 is {% url 'index' area='ab-12-cd' %}").render(Context())
输出
u'url1 is /'
u'url2 is /area/1'
u'url3 is /area/ab-12-cd'