2013-07-23 189 views
5

假設我有一個包含模板頭的基模板,並且該模板需要傳遞該模板的內容。Jinja2和Flask:將變量傳遞給父模板而不傳遞給子模塊

<header> 
    You are logged in as {{ name }} 
</header> 

此基本模板被許多頁面擴展。我怎麼能通過這個變量而不將它傳遞給每個孩子?例如,我不想這樣做:

render_template("child1.html", name=user.name) 
render_template("child2.html", name=user.name) 
render_template("child3.html", name=user.name) 
etc... 

因爲誰知道我可能有多少個子頁面。它感覺不夠乾燥。

我從來沒有實際渲染基本模板,只有它的子項,但我不知道如何傳遞數據。

有沒有辦法做到這一點?我應該不使用繼承嗎?

回答

9

我可以建議你在燒瓶中使用全局變量'g'。這在jinja模板中默認是可用的。所以你不需要擔心在基本模板或孩子的任何地方傳遞它。只要確保你第一次設置它,當你登錄

g.username = user.name 

然後在模板,只是這樣做:

You are logged in as {{ g.username }} 
+1

最新燒瓶版本(我相信從0.10開始)給這個錯誤:'RuntimeError:在應用程序上下文之外工作「。任何人都知道如何處理它? –

1

您需要使用瓶的context-processors

@app.context_processor 
def inject_user(): 
    return dict(user=g.user) 

看到這個類似SO question and answer

的我如何使用它的一個例子(簡單地插入應用程序配置設置):

@app.context_processor 
def lib_versions(): 
    return dict(
     bokehversion = app.config['BOKEH_VERSION'], 
     jqueryversion = app.config['JQUERY_VERSION'], 
     jqueryuiversion = app.config['JQUERYUI_VERSION'], 
     bootstrapversion = app.config['BOOTSTRAP_VERSION'], 
    ) 

這是從我的瓶配置文件拉:

class Config(object): 
    DEBUG = True 
    TESTING = True 
    SQLALCHEMY_DATABASE_URI = '' 
    TMP_DIR = '' 
    STATIC_FOLDER = '' 
    BOKEH_VERSION = '0.8.2' 
    JQUERY_VERSION = '1.11.2' 
    JQUERYUI_VERSION = '1.11.4' 
    BOOTSTRAP_VERSION = '3.3.4' 

class ProductionConfig(Config): 
    DEBUG = False 
    TESTING = False 

在你然後調用這些你基本模板就像任何其他Jinja2變量:

<!-- START: CSS --> 
<link rel="stylesheet" media="screen" type="text/css" href="http://cdn.pydata.org/bokeh/release/bokeh-{{ bokehversion }}.min.css"> 
<!-- END: CSS --> 
<!-- START: JS --> 
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/{{ jqueryversion }}/jquery.min.js"></script> 
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/{{ jqueryuiversion }}/jquery-ui.min.js"></script> 
<script type="text/javascript" src="//maxcdn.bootstrapcdn.com/bootstrap/{{ bootstrapversion }}/js/bootstrap.min.js"></script> 
<!-- END: JS -->