【问题标题】:styling active element menu in flask在烧瓶中设置活动元素菜单的样式
【发布时间】:2014-04-06 01:15:17
【问题描述】:

我在烧瓶中有以下模板结构:

templates/
  /posts
    list.html
  base.html
  index.html

我的 base.html:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>ITV</title>
    <!-- Latest compiled and minified CSS -->
    <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
    <link rel="stylesheet" href="{{ url_for('static', filename='css/main.css') }}">

    <!-- Latest compiled and minified JavaScript -->
    <script src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
</head>

<body>

{%- block topbar -%}
    <nav class="navbar navbar-default navbar-static-top" role="navigation">
      <!-- We use the fluid option here to avoid overriding the fixed width of a normal container within the narrow content columns. -->
      <div class="container-fluid">
        <div class="navbar-header">
          <a class="navbar-brand" href="/">САПР</a>
        </div>

        <!-- Collect the nav links, forms, and other content for toggling -->
        <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-8">
          <ul class="nav navbar-nav">
            <li class="active"><a href="/">Головна</a></li>
            <li><a href="/posts">Новини</a></li>
            <li><a href="/schedue">Розклад занять</a></li>
          </ul>
        </div><!-- /.navbar-collapse -->
      </div>
    </nav>
{%- endblock -%}

<div class="container">
    <div class="content">
        {% block page_header %}{% endblock %}
        {% block content %}{% endblock %}
    </div>
</div>
</body>
</html>

我可以渲染模板,例如:render_template('posts/list.html'),它扩展了我的base.html

我的列表.html:

{% extends "base.html" %}

{% block content %}

    Posts
{% endblock %}

如何在 base.html 中设置活动元素菜单

        <li class="active"><a href="/">Головна</a></li>
        <li><a href="/posts">Новини</a></li>
        <li><a href="/schedue">Розклад занять</a></li>

当我渲染 list.html 时,不能直接将数据传递到 base.html 中?

【问题讨论】:

    标签: flask


    【解决方案1】:

    在 Flask 中,request 变量在模板中是 available by default,因此您只需在 base.html 中检查 request.path 并调整您的链接。

    <li {% if request.path == '/' %}class="active"{% endif %}>
         <a href="/">Головна</a>
    </li>
    

    【讨论】:

    • 最好使用url_for 而不是只使用文字'/'。这样,如果您更改了路由端点,您只需在一个地方更改它。另一方面,如果您更改该端点的方法名称,现代 IDE(如 PyCharm)也会重构 HTML 模板中 url_for 调用中的方法名称。
    【解决方案2】:

    也可以使用三元...只是更短一些更好

    <li {{ 'class="active"' if request.path == '/' else '' }}>
         <a href="/">Головна</a>
    </li>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-04-12
      • 1970-01-01
      • 1970-01-01
      • 2020-04-17
      • 2012-07-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多