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

标签 python django django-templates django-urls

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

`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/

相关文章:

javascript - 使用 selenium 检查 javascript 异常?

python - 寻找最低未使用号码的优雅和简短(pythonic)方式

python - 为什么 scipy.signal.welch 会抑制零频率?

python - python中的 boolean 文本搜索

django - 如何使用 Bitnami 为 django 应用程序启用 SSL?

python - 当 django admin 中某个字段发生变化时执行操作

python - Django 临时图像

python - 如何使用 django Rest-auth View 和自定义 html 模板而不是可浏览的 API

django - 为什么 django 中的 Simple 标签不起作用?

Django FormView 没有表单上下文