【问题标题】:Django along with bootstrap navbar - distiinguishing link to current pageDjango 和引导导航栏 - 区分当前页面的链接
【发布时间】:2015-07-14 01:45:54
【问题描述】:

我将引导程序用于我的 django 项目。 我有一个这样的导航栏:

[home][gallery][user]

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

例如,如果我在主页上,主页按钮会突出显示。

【问题讨论】:

    标签: django twitter-bootstrap


    【解决方案1】:

    解决方案 1

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

    例如

    # 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>
    

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

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

    解决方案 2

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

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

    在您的模板中,您可以使用{{ current_path }} 来确定应该激活哪个导航项。

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

    【讨论】:

    • 感谢您提供这些解决方案。
    猜你喜欢
    • 1970-01-01
    • 2016-10-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-31
    • 2023-02-06
    • 2021-01-01
    • 1970-01-01
    • 2021-11-19
    相关资源
    最近更新 更多