删除 Django 模板中指向当前页面的链接

Remove links to current page in Django tamplate

我有一个 Django 模板 (list.html),其中包括这些 links

  <a href="{% url 'notifications:list' %}" role="button">All</a> |
  <a href="{% url 'notifications:list_unread' %}" role="button">Unread</a> |
  <a href="{% url 'notifications:read_all' %}" role="button">Mark all read</a>

其中两个视图(notifications:list 和 notifications:list_unread)使用此模板,但发送不同的查询集进行显示。

如何使用 Django 模板语言将 link 移除到当前视图?

例如,如果我在“列表”视图中,我会看到:

未读 |全部标记为已读

如果我在 'list_unread' 视图中,我会看到:

全部|全部标记为已读

或者有更好的方法吗?这似乎是一项常见的任务。

您可以将一个变量传递给 context 并检查它是否在您的模板中以禁用 link.

通知列表视图:

在您的通知列表视图中,您可以将变量 notifications_list 传递给您的模板。

class NotificationsListView(..):

    def get_context_data(self):
        context = super(NotificationListView).get_context_data()
        context['notifications_list'] = True
        return context

然后在您的模板中,您可以执行以下操作:

{% if not notifications_list %}
    <a href="{% url 'notifications:list' %}" role="button">All</a> |
{% else %}
    <a href="{% url 'notifications:list_unread' %}" role="button">Unread</a> |
{% endif %}
<a href="{% url 'notifications:read_all' %}" role="button">Mark all read</a>

因此,每当请求通知列表视图时,list link 将被禁用并显示 list_unread link。

如果是list_unread请求,listlink会显示,list_unreadlink不会显示。

这是一种在模板中直接执行此操作的方法,将前两个链接显示为有条件的:

  {% url 'notifications:list' as list_url %}
  {% if request.path != list_url %}
    <a href="{{list_url}}">All</a> |
  {% endif %}
  {% url 'notifications:list_unread' as list_unread_url %}
  {% if request.path != list_unread_url %}
    <a href="list_unread_url" >Unread</a> |
  {% endif %}
  <a href="{% url 'notifications:read_all' %}">Mark all read</a>

h/t: