2017-12-18 284 views
-1

我有一個渲染頁面,我一個簡單的瓶功能:是否可以在render_template之前將數據傳遞給Flask?

@app.route('/') 
def main_page(): 
    return render_template("index.html") 

我的問題是,是否有可能從它位於我index.html文件傳回瓶的main_page功能的JavaScript函數傳遞變量在它完全呈現之前?

這裏是我的html文件:

<head> 
    <title>My Title</title> 
</head> 
<body> 
// HTML content 
<script> 
firebase.auth().onAuthStateChanged(firebaseUser => { 
    if (firebaseUser) { 
     var myVar = "content" 
    } 
}); 
</script> 
</body> 

我想是這樣的:

@app.route('/') 
def main_page(): 
    # 1. get the myVar variable from the JS code located in the same index.html page 
    # 2. check the variable and pass a variable to the Jinja template based on myVar's content 
    if myVar is something: 
     return render_template("index.html", text = "something A") 
    else: 
     return render_template("index.html", text = "something B") 

所以我不希望獲得來自文本框的內容,我會接受嗎通過JS代碼。我想加載一次'/'路由,並根據myVar變量的內容決定要傳入Jinja模板的數據。如果這是不可能的,是否有任何技巧或替代技術可以產生幾乎相同的結果?

+0

我認爲你將不得不提交您的狀態變化的POST請求到端點並把它傳遞給模板 – Adam

+0

@Adam這很有趣,我曾與文本框的做到了這一點,當你有渲染頁面,那麼你獲取文本字段的內容並執行一些操作。但在頁面加載時無法使其工作。恐怕這是不可能的。 – rihe

+0

我其實誤解了這個問題。我沒有意識到它是在渲染之前,因此在它服務之前。我想我很好奇,爲什麼你不處理路由中的變量,然後將它傳遞到模板上下文 – Adam

回答

1

鑑於您正在訪問第三方API並且未將應用程序中的任何數據保存到數據庫,因此不需要將HTTP請求發送回瓶型應用程序。狀態可以在客戶端處理,只需更新HTML w/JQuery即可。

// in callback 
$('target').val('newval'); 
相關問題