简体   繁体   English

Django URL名称在模板中使用

[英]Django URL names use in Templates

Right now in my templates I hardcore the links in my navigation like the following: 现在,在我的模板中,我将导航中的链接硬着如下:

`base.html`

<a href="/about">About</a>
<a href="/contact">Contact</a>
<!-- etc -->

In my urls.py 在我的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'),
 )

Is there a way that in my base.html file reference the urlpatterns from urls.py so that anytime I change those, it reflects everywhere across my pages and templates?? 有没有办法在我的base.html文件中引用urls.py的urlpatterns,以便我随时更改它们,它反映了我的页面和模板的所有地方? Something like 就像是

<!-- what I would like to do -->
<a href="{{ reference_to_about_page }}">About</a>
<a href="{{ reference_to_contact_page }}">About</a>

This is why url tag was invented: 这就是发明url标签的原因:

Returns an absolute path reference (a URL without the domain name) matching a given view function and optional parameters. 返回与给定视图函数和可选参数匹配的绝对路径引用(不带域名的URL)。

If you're using named URL patterns, you can refer to the name of the pattern in the url tag instead of using the path to the view. 如果您使用的是命名URL模式,则可以在url标记中引用模式的名称,而不是使用视图的路径。

This basically means that you can use url names configured in the urlpatterns in the url tag: 这基本上意味着您可以使用url标记中的urlpatterns中配置的URL名称:

<a href="{% url 'about' %}">About</a>
<a href="{% url 'contact' %}">Contact</a>

This gives you more flexibility. 这为您提供了更大的灵活性 Now any time the actual url of about or contact page changes, templates would "catch up" the change automagically. 现在,只要aboutcontact页面的实际网址发生变化,模板就会自动“赶上”变更。

Use Django's url template tag (docs here ) with your named url pattern. 使用Django的url模板标记( 此处为docs)和您的命名url模式。

Example: 例:

<a href="{% url 'about' %}">About</a>
<a href="{% url 'contact' %}">Contact</a>

Note that the name you put in ' ' will be the name of the particular url pattern in your urls.py . 请注意,你把名字' '将是name在特定的URL模式的urls.py Also, if this is the urls.py file in an app (that is, it gets routed initially from the base urls.py ), you'll need to include the namespacing of the app. 此外,如果这是应用程序中的urls.py文件(也就是说,它最初从基础urls.py路由),则需要包含应用程序的命名空间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM