twitter-bootstrap 使用 python/flask 中的 twitter bootstrap css 更改链接的活动类

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18600031/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 18:14:09  来源:igfitidea点击:

Changing the active class of a link with the twitter bootstrap css in python/flask

pythonclasstwitter-bootstrapflaskjinja2

提问by Azeirah

I got the following html snippet from my page template.html.

我从我的页面中得到了以下 html 片段template.html

<ul class='nav'>
    <li class="active"><a href='/'>Home</a></li>
    <li><a href='/lorem'>Lorem</a></li>

    {% if session['logged_in'] %}
        <li><a href="/account">Account</a></li>
        <li><a href="/projects">Projects</a>
        <li><a href="/logout">Logout</a></li>
    {% endif %}

    {% if not session['logged_in'] %}
        <li><a href="/login">Login</a></li>
        <li><a href="/register">Register</a></li>
    {% endif %}
</ul>

As you can see on line 2, there's the class active. This highlights the active tab with the twitter bootstrap css file. Now, this will work fine if I would visit www.page.com/but not when I would visit www.page.com/loginfor example. It would still highlight the home link as the active tab.

正如您在第 2 行看到的那样,该类处于活动状态。这将突出显示带有 twitter bootstrap css 文件的活动选项卡。现在,这在我访问www.page.com/时会正常工作,但在我访问时则不会www.page.com/login。它仍然会将主页链接突出显示为活动选项卡。

Of course, I could easily do this with Javascript/jQuery but I'd rather not use that in this situation.

当然,我可以使用 Javascript/jQuery 轻松做到这一点,但在这种情况下我宁愿不使用它。

There's already a working solution for ruby on railsbut I don't know how to convert that into python/jinja (I'm rather new to jinja/flask, never worked with ruby at all)

ruby on rails已经有一个可行的解决方案,但我不知道如何将其转换为 python/jinja(我对 jinja/flask 很陌生,从来没有使用过 ruby​​)

回答by codegeek

Have you looked at this ? http://jinja.pocoo.org/docs/tricks/

你看过这个吗?http://jinja.pocoo.org/docs/tricks/

Highlighting Active Menu Items

突出显示活动菜单项

Often you want to have a navigation bar with an active navigation item. This is really simple to achieve. Because assignments outside of blocks in child templates are global and executed before the layout template is evaluated it's possible to define the active menu item in the child template:

通常,您希望有一个带有活动导航项的导航栏。这真的很容易实现。因为子模板中块之外的分配是全局的,并且在评估布局模板之前执行,所以可以在子模板中定义活动菜单项:

{% extends "layout.html" %}
{% set active_page = "index" %}

The layout template can then access active_page. Additionally it makes sense to define a default for that variable:

然后布局模板可以访问active_page. 此外,为该变量定义默认值是有意义的:

{% set navigation_bar = [
    ('/', 'index', 'Index'),
    ('/downloads/', 'downloads', 'Downloads'),
    ('/about/', 'about', 'About')
] -%}

{% set active_page = active_page|default('index') -%}
...
<ul id="navigation">
    {% for href, id, caption in navigation_bar %}
    <li{% if id == active_page %} class="active"{% endif
    %}><a href="{{ href|e }}">{{ caption|e }}</a>
    </li>
{% endfor %}
</ul>

回答by varun

Here is another simpler way if you have menus distributed all over the page. This way uses inline if statements to print out the class active.

如果您的菜单分布在整个页面上,这是另一种更简单的方法。这种方式使用内联 if 语句打印出类active

<ul>

<li class="{{ 'active' if active_page == 'menu1' else '' }}">
<a href="/blah1">Link 1</a>
</li>

<li class="{{ 'active' if active_page == 'menu2' else '' }}">
<a href="/blah2"> Link 2 </a>
</li>

</ul>

Class active is for highlighting

类 active 用于突出显示

You still need to set the variable on every page to mark them

您仍然需要在每个页面上设置变量来标记它们

{% extends "master.html" %}
{% set active_page = "menu1" %}

or

或者

{% set active_page = "menu2" %}

回答by philmaweb

For jinja/flask/bootstrapusers:

对于jinja/flask/bootstrap用户:

If you define your nav like they did in the blog example http://getbootstrap.com/examples/blog/simply assign ids to your links that match your url_forarguments and you just need to modify the layout-template, the rest just works #magic.

如果您像在博客示例http://getbootstrap.com/examples/blog/ 中那样定义您的导航, 只需将 id 分配给与您的url_for参数匹配的链接,您只需要修改布局模板,其余的就可以了#魔法。

<nav class="blog-nav">
  <a id="allposts"  class="blog-nav-item" href="{{ url_for('allposts')}}">All Posts</a>
  <a id="index"     class="blog-nav-item" href="{{ url_for('index')}}">Index</a>
  <a id="favorites" class="blog-nav-item" href="{{ url_for('favorites')}}">Favorites</a>
</nav>

At the bottom of your base/layout template just add this

在你的基础/布局模板的底部添加这个

<script>
  $(document).ready(function () {
  $("#{{request.endpoint}}").addClass("active"); })
</script>

and the right elements will be set active.

并且正确的元素将被设置为活动状态。

EDIT:If you have a layout with elements in a list, like this:

编辑:如果您的布局包含列表中的元素,如下所示:

<nav class="blog-nav">
  <ul class="nav navbar-nav">
    <li>
        <a id="allposts"  class="blog-nav-item" href="{{ url_for('allposts')}}">All Posts</a>
    </li>
    <li>
        <a id="index"     class="blog-nav-item" href="{{ url_for('index')}}">Index</a>
    </li>
    <li>
        <a id="favorites" class="blog-nav-item" href="{{ url_for('favorites')}}">Favorites</a>
    </li>
  </ul>
</nav>

use the parent() function to get the li element instead of the link.

使用parent()函数获取 li 元素而不是链接。

<script>
    $(document).ready(function () {
    $("#{{request.endpoint}}").parent().addClass("active"); })
</script>

回答by Nick K9

I liked @philmaweb's approach, but there's really no reason to require duplicating the endpoint in the id of each element.

我喜欢@philmaweb的方法,但真的没有理由要求在每个元素的 id 中复制端点。

base.js:

基础.js:

$(document).ready(function () {
    var scriptElement = $('#baseScript')[0];
    var path = scriptElement.getAttribute('data-path');
    $('a[href="'+path+'"]').addClass("active");
});

base.html

基本文件

<script id="baseScript" src="{{ url_for('static', filename='js/base.js') }}"
data-path="{{ request.path }}"></script>

Why not just put this script inline? You could, of course, but allowing inline JS is a security nightmare. You should be using a CSP on your site (e.g. Flask-Talisman) which will not allow inline JS. With data-*attributes, it's not hard to do this in a secure way.

为什么不把这个脚本内联?你当然可以,但允许内联 JS 是一个安全噩梦。您应该在您的站点上使用 CSP(例如Flask-Talisman),它不允许内联 JS。使用data-*属性,以安全的方式做到这一点并不难。

NB: If you have multiple links leading to the same, current page and you want only ONE of them to be marked "active"—then this approach may not work for you.

注意:如果您有多个链接指向同一个当前页面,并且您只想将其中一个标记为“活动”——那么这种方法可能不适合您。

回答by B Donald

Add the following CSS somewhere on your page:

在页面的某处添加以下 CSS:

a[href $= {{ page_name|default("'/'"|safe) }}]{ [INSERT YOUR ACTIVE STYLING HERE] }

a[href $= {{ page_name|default("'/'"|safe) }}]{ [INSERT YOUR ACTIVE STYLING HERE] }

Now, on each template define page_name, for example:

现在,在每个模板上定义page_name,例如:

{% extends "template.html" %} {% set page_name = "gallery" %}

{% extends "template.html" %} {% set page_name = "gallery" %}

This seems much simpler and easier to build on, than other options.

与其他选项相比,这似乎更简单、更容易构建。

EDIT:

编辑:

Almost 1 year later I'm returning to make this a much simpler fix, because setting the page name on every page is pretty inefficient.

将近 1 年之后,我又回来做了一个更简单的修复,因为在每个页面上设置页面名称非常低效。

Instead create a function like so:

而是创建一个像这样的函数:

@app.context_processor
def context_processor():
    out = {}
    out['request'] = request # Make sure you import request from flask
    return out

This will allow you to pass variables implicitly to jinja, in this case we are passing the request for access to request.url_rulewhich contains the route the user is accessing. In the previous version, we just change {{ page_name|default("'/'"|safe) }}to "{{ request.url_rule|safe }}". Much cleaner.

这将允许您将变量隐式传递给 jinja,在这种情况下,我们将传递request.url_rule包含用户正在访问的路由的访问请求。在之前的版本中,我们只是{{ page_name|default("'/'"|safe) }}改为"{{ request.url_rule|safe }}". 干净多了。