【问题标题】:How to add a class ACTIVE by using django template?如何使用 django 模板添加一个 ACTIVE 类?
【发布时间】:2016-09-21 08:18:27
【问题描述】:
<div class="menu-top" style="width:715px;">
  <ul class="nav nav-pills">
    <li>
      <a href="/link1"
      {% if request.path == '/phylosophy' %}class="active"{% endif %}>
      philosophy
      </a>
    </li>
    <li><a href="/link2"><u>{% trans 'product' %}</u></a></li>
    <li><a href="/link3"><u>{% trans 'contact' %}</u></a></li>
    <li><a href="/link4"><u>{% trans 'news' %}</u></a></li>
  </ul>
</div>

我需要将 .active 类添加到标签中。我做错了什么?

【问题讨论】:

标签: django django-templates


【解决方案1】:

通常 Django 会将/ 附加到 URL,因此可能会更改为:

{% if request.path == '/phylosophy/' %}class="active"{% endif %}>

额外:

这种方法的问题是,如果您有更深的 URL,例如 /phylosophy/list/,您可能仍希望保留 active 类,所以我通常会创建一个名为 startswith 的模板标签:

@register.filter('startswith')
def startswith(text, starts):
    if isinstance(text, basestring):
        return text.startswith(starts)
    return False

然后像这样使用它:

<li{% if request.path|startswith:'/phylosophy/' %} class="active"{% endif %}>

PS:

如果打印时 request.path 为空,您可能需要将其添加到上下文处理器 (django.template.context_processors.request),例如:

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'APP_DIRS': True,
        'DIRS': (
            PROJECT_DIR.child('templates'),
        ),
        'OPTIONS': {
            'context_processors': [
                'django.contrib.auth.context_processors.auth',
                'django.template.context_processors.debug',
                'django.template.context_processors.i18n',
                'django.template.context_processors.media',
                'django.template.context_processors.static',
                'django.template.context_processors.tz',
                'django.contrib.messages.context_processors.messages',
                'django.template.context_processors.request',
            ],
            'debug': DEBUG
        }
    },
]

【讨论】:

    猜你喜欢
    • 2017-10-20
    • 1970-01-01
    • 2011-02-24
    • 1970-01-01
    • 2022-01-21
    • 1970-01-01
    • 2015-02-15
    • 2020-11-05
    • 1970-01-01
    相关资源
    最近更新 更多