cus*_*ice 3 python django django-templates django-urls
现在,在我的模板中,我将导航中的链接硬着如下:
`base.html`
<a href="/about">About</a>
<a href="/contact">Contact</a>
<!-- etc -->
Run Code Online (Sandbox Code Playgroud)
在我的 urls.py
urlpatterns = patterns('',
url(r'^about/$', TemplateView.as_view(template_name='pages/about.html'), name='about'),
url(r'^contact/$', TemplateView.as_view(template_name='pages/contact.html'), name='contact'),
)
Run Code Online (Sandbox Code Playgroud)
有没有办法在我的base.html文件中引用urlpatterns,urls.py以便我随时更改它们,它反映了我的页面和模板的所有地方?就像是
<!-- what I would like to do -->
<a href="{{ reference_to_about_page }}">About</a>
<a href="{{ reference_to_contact_page }}">About</a>
Run Code Online (Sandbox Code Playgroud)
这就是url标签发明的原因:
返回与给定视图函数和可选参数匹配的绝对路径引用(不带域名的URL).
如果您使用的是命名URL模式,则可以在url标记中引用模式的名称,而不是使用视图的路径.
这基本上意味着你可以使用配置的URL名称urlpatterns的url标签:
<a href="{% url 'about' %}">About</a>
<a href="{% url 'contact' %}">Contact</a>
Run Code Online (Sandbox Code Playgroud)
这为您提供了更大的灵活性 现在,只要实际的网址about或contact页面发生变化,模板就会自动"赶上"变化.
将 Django 的url模板标签(此处的文档)与您的命名 url 模式结合使用。
例子:
<a href="{% url 'about' %}">About</a>
<a href="{% url 'contact' %}">Contact</a>
Run Code Online (Sandbox Code Playgroud)
请注意,您输入的名称' '将是name您的urls.py. 另外,如果这是urls.py应用程序中的文件(即,它最初是从 base 路由的urls.py),则您需要包含应用程序的命名空间。