gpt4 book ai didi

python - 模板中使用的 Django URL 名称

转载 作者:太空宇宙 更新时间:2023-11-03 13:44:25 24 4
gpt4 key购买 nike

现在在我的模板中,我将导航中的链接硬核化,如下所示:

`base.html`

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

在我的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'),
)

有没有一种方法可以在我的 base.html 文件中引用 urls.py 中的 urlpatterns,这样每当我更改它们时,它就会在我的页面和模板中无处不在??有点像

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

最佳答案

这就是为什么 url标签被发明:

Returns an absolute path reference (a URL without the domain name) matching a given view function and optional parameters.

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 标记中使用在 urlpatterns 中配置的 url 名称:

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

这为您提供了更大的灵 active 。现在,只要 aboutcontact 页面的实际 url 发生变化,模板就会自动“ catch ”变化。

关于python - 模板中使用的 Django URL 名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23419289/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com