Django 和引导导航栏 - 区分当前页面的链接 [英] Django along with bootstrap navbar - distiinguishing link to current page

查看:26
本文介绍了Django 和引导导航栏 - 区分当前页面的链接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 django 项目使用引导程序.我有一个这样的导航栏:

[home][gallery][user]

如何更改特定导航栏按钮的 CSS 属性以对应当前打开的页面?

例如,如果我在主页上,主页按钮将突出显示.

解决方案

解决方案 1

我通常将导航栏模板包含在所有模板中,每个模板都应该定义页面是什么.

例如

# nav.html<div class=".."><div class="..">我的导航</div><ul class=".."><a href=".." class=".. {% if active == 'home' %} active {% endif %}">Home</a><a href="/settings/" class="list-group-item {% if active == 'settings' %} active {% endif %}">Settings</a>

然后在每个模板中指定哪个应该是活动的.像这样的东西

# home.html{% 包含 "yourtemplatedir/nav.html" 和 active='home' %}# 设置.html{% 包括yourtemplatedir/nav.html"和 active='settings' %}

<小时>

解决方案 2

使用上下文处理器有时会很容易

def get_current_path(request):返回 {'current_path': request.get_full_path()}

在您的模板中,您可以使用 {{ current_path }} 来确定哪个导航项目应该处于活动状态.

您还可以增强上下文处理器代码,以检查 url 的前缀并自动设置 active_page 变量.所以你不需要为每个包含设置它(如果你总是在你的基础中包含 nav.html ).然而,这里真的很难有例外.

I use bootstrap for my django project. I have a navbar like this:

[home][gallery][user]

How can I change the CSS properties of a specific navbar button to correspond to a currently opened page?

For example, if I am on the home page, the home button would be highlighted.

解决方案

Solution 1

I usually have the navbar template gets included in all templates, each template should define what the page is this.

For example

# nav.html

<div class="..">
    <div class="..">My Nav</div>
        <ul class="..">
            <a href=".." class=".. {% if active == 'home' %} active {% endif %}">Home</a>
            <a href="/settings/" class="list-group-item {% if active == 'settings' %} active {% endif %}">Settings</a>
        </ul>
</div>

Then in each template you specify which should be active. something like this

# home.html 

{% include "yourtemplatedir/nav.html" with active='home' %}


# settings.html 

{% include "yourtemplatedir/nav.html" with active='settings' %}


Solution 2

Using context processor will make it sometimes easy

def get_current_path(request):
    return {
       'current_path': request.get_full_path()
     }

In your template you can use {{ current_path }} to determine which nav item should be active.

You can also enhance the context processor code in order to check the prefix of the url and set the active_page variable automatically. so you don't need to set it with each include (In case you include the nav.html in your base always). However it really hard to have exceptions in here.

这篇关于Django 和引导导航栏 - 区分当前页面的链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆