django 模板锚标记不起作用

Ash*_*ish 1 python django django-templates django-urls

我的网页中有一个标题,该标题中有一个徽标。我想在该徽标中插入一个锚标记,该标记指向我的主页,即 index.html 页面,尽管调用了哪个视图或页面。我创建了一个 base.html,其中的一个片段是:

<div class="header">
            <div class="inner_header">
                <div class="logo">

                    <a href='#'><img src="{% static 'images/logo.png' %}" alt="logo" /> </a>

                </div>
Run Code Online (Sandbox Code Playgroud)

我已将此 base.html 扩展到所有其他模板文件

我指向我的索引页和其他页面的 url 模式是这样的:

 urlpatterns = patterns('',
        url(r'^$', views.index, name='index'),
        url(r'^category/(?P<category_name_slug>[\w\-]+)/$', views.category, name='category'),
        url(r'^latest/(?P<latest_title_slug>[\w\-]+)/$', views.latest, name='latest'),
        url(r'^headline/(?P<heading_title_slug>[\w\-]+)/$', views.headline, name='headline'),)
Run Code Online (Sandbox Code Playgroud)

我试过使用<a href="index.html">,<a href=''>和其他一堆不会产生预期结果或给出错误的东西。在不编写大量代码的情况下执行此操作的适当方法是什么?

Say*_*yse 5

Rohit Jain 使用url模板标签的建议是正确的

<a href="{% url 'index' %}">
Run Code Online (Sandbox Code Playgroud)

但这可能有助于了解您当前的方法正在做什么

  • <a href='#'>- 这是试图链接到您页面上的 id 元素,但由于您没有提供 id 名称,它只是指页面本身。它不会重定向到任何地方
  • <a href="index.html"> - 您正在尝试直接引用模板,您没有将这个 url 映射到一个视图,然后显示该模板的 urlpattern
  • <a href=''>- 这与使用几乎相同,#因为您没有更改要附加到的链接

您可能会取得一些成功,<a href="/">但同样,这不是在 django 中执行此操作的正确方法,因为您将来可能决定更改与特定视图匹配的 url 模式(即您决定添加 i18n 模式),因此您应该总是尝试使用url模板标签。