[英]Flask: passing multiple python based variables through render_template()
試圖讀取我在python / a Flask視圖函數中創建的兩個變量時,行為變得越來越令人沮喪。
我有一個名為Python程序experiment.py
。 有一個路由到POST請求的函數,當有人提交表單時會執行該函數。 在該函數中,我試圖返回兩個變量:“ user_id”和“ total_trials”,其中“ user_id”包含一個生成的user_id,該“ total_trials”實際上與用戶輸入的前一表格中的試驗次數相同。
我嘗試了兩種方法來返回這些變量。 當前的方法是使用render_template()中的data
參數,並將這些變量填充到字典中。
@bp.route('/experiment_app', methods=['GET', 'POST'])
def exp_js_psych_app():
total_trials = int(request.form['trials'])
import random
import string
# Generate a random string
# with 8 characters.
user_id = ''.join([random.choice(string.ascii_letters
+ string.digits) for n in range(8)])
user_id = str(user_id)
generate_stim_for_trials(total_trials, user_id)
return render_template("index.html", data={"user_id": str(user_id), "total_trials":total_trials})
#return render_template("index.html", user_id=user_id, total_trials=total_trials) # also tried to merely just return both variables individually
因此,我試圖將這兩個變量都放入index.html上的某些內聯javascript中。 這是代碼。
<!DOCTYPE html>
<html>
<head>
<title>My experiment</title>
<script type="text/javascript">
// var trial_total = {{ total_trials }};
var trial_total = {{ data.total_trials }};
console.log(trial_total);
// var user_id = {{ user_id }};
var user_id = String( {{ data.user_id }} ) ;
console.log("USER ID HTML");
console.log(user_id);
</script>
</head>
<body></body>
</html>
您可以看到我已注釋掉
我能夠在兩種方法中成功提取total_trials
變量,沒問題。
問題與user_id一起出現。 不管我做什么... {{ data.user_id }}
或{{ user_id }}
實際上確實返回在python中生成的字符序列。 但是問題在於這些字符序列不在字符串中/沒有引號,它們只是像變量名一樣出現。 因此,如果將python應用程序中的user_id
設置為字符串“ 12345678”,則在Javascript中,當我使用Jinja語法引用user_id
或data.user_id
我只會得到12345678
,這通常會觸發“無法識別的變量”錯誤。
這是我使用inspect元素的屏幕截圖(試圖檢查控制台)以顯示我的意思
如果嘗試使用String
,我將得到以下信息: var user_id = String(6z9dVPpG);
。
所以...這是什么問題?
請注意,如果嘗試使用{{ data.user_id|string }}
我仍然會在控制台中得到與屏幕快照相同的結果。
嘆
我不知道為什么會這樣,但是... var user_id = "{{ data.user_id|string }}";
作品。 因此,用引號將表達式引起來。
使用Jinja表達式引用字符串時是否需要引號?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.