2015-10-28 21 views
0

一切工作正常,包括標題,直到我去添加圖標英寸。手動創建<head>並呼籲{{ super() }}引入Bootstrap的黑魔法,標題現在顯示在導航欄上方。爲什麼在使用Flask時頁面正文中顯示標題?

base.html文件

{% extends "bootstrap/base.html" %} 

{% block head %} 
    {{ super() }} 
    {% block title %}{% block page_name %}{% endblock %} - MyFlask{% endblock %} 
    <link rel="icon" href="{{ url_for('static', filename='favicon.ico') }}" type="image/x-icon"> 
    <link rel="shortcut icon" href="{{ url_for('static', filename='favicon.ico') }}" type="image/x-icon"> 
{% endblock %} 

<body> 
    {% block navbar %} 
     <nav class="navbar navbar-default"> 
      <div class="container-fluid"> 
       <div class="navbar-header"> 
        <a class="navbar-brand" href="#">MyFlask</a> 
       </div> 
      </div> 
     </nav> 
    {% endblock %} 
</body> 

的index.html

{% extends "base.html" %} 

{% block page_name%}Index{% endblock %} 
+0

你可能包括「引導/基地。 html「文件? – ojii

+0

Bootstrap/base.html文件是Bootstrap附帶的標準文件。據我所知,我認爲它只是包含了所有的設置和初始化,以便合併Bootstrap。這實際上可能是它繼承的文件(a.k.a bootstrap/base.html),至少有一些非常相似。 https://github.com/mbr/flask-bootstrap/blob/master/flask_bootstrap/templates/bootstrap/base.html – Jordan

回答

1

當你在一個塊中使用super()功能,您要添加新的內容,以該塊,而不是被替換的內容。所以,當你在head塊稱爲super(),Jinja2的插入從bootstrap/base.htmlhead塊的內容:

<head> 
    {%- block head %} 
    <title>{% block title %}{% endblock title %}</title> 

    {%- block metas %} 
    <meta name="viewport" content="width=device-width, initial-scale=1.0"> 
    {%- endblock metas %} 

    {%- block styles %} 
    <!-- Bootstrap --> 
    <link href="{{bootstrap_find_resource('css/bootstrap.css', cdn='bootstrap')}}" rel="stylesheet"> 
    {%- endblock styles %} 
    {%- endblock head %} 
    </head> 

之後,你增加了一個新的title塊,所以現在你有兩個人,這就是問題所在。

這種方案很容易,不base.html定義一個新的head塊,只是重寫title塊,你的圖標行追加到styles

{% extends "bootstrap/base.html" %} 

{% block title %}{% block page_name %}{% endblock %} - MyFlask{% endblock %} 

{%- block styles %} 
{{ super() }} 
<link rel="icon" href="{{ url_for('static', filename='favicon.ico') }}" type="image/x-icon"> 
<link rel="shortcut icon" href="{{ url_for('static', filename='favicon.ico') }}" type="image/x-icon"> 
{% endblock %} 

{% block navbar %} 
    <nav class="navbar navbar-default"> 
     <div class="container-fluid"> 
      <div class="navbar-header"> 
       <a class="navbar-brand" href="#">MyFlask</a> 
      </div> 
     </div> 
    </nav> 
{% endblock %} 
0

我懷疑這並不直接回答你的問題,但也許一個實現的更好的方法這個結果是從視圖中傳遞頁面標題。

base.html

{% block title %} 
    {% if title %} 
     {{title}} - MyFlask 
    {% else %} 
     MyFlask 
    {% endif %} 
{% endblock %} 

views.py

@app.route('/', methods=['GET']) 
def index(): 
    return render_template("index.html", title='Index') 
相關問題