将值传递到进度条(Twitter Bootstrap, Flask)
我正在使用Twitter Bootstrap来绘制一个进度条,但我想指定进度的具体数值。为此,我使用了一个Python字符串,叫做thePercent,它通过Flask传递到HTML中。
thePercent:
"width: 35%"
目前,我的predictions.html文件看起来是这样的:
<div class="progress">
<div class="progress-bar" role="progressbar" aria-valuenow="60" aria-valuemin="0" aria-valuemax="100" style="width: 90%;">
<span class="sr-only">{{thePercent}}% Complete</span>
</div>
</div>
我的view.py文件看起来是这样的:
@app.route("/result")
def resultpage():
IDnumber = int(request.args.get('ID'))
with db:
cur = db.cursor()
cur.execute("SELECT AnimalID, AdoptionProbability FROM Demo_Data WHERE AnimalID = '" + str(IDnumber) + "' LIMIT 1")
query_results = cur.fetchall()
thePercent= str(int(query_results[0][1]))
theDog = "static/PetPics/" + str(int(query_results[0][0]))
print thePercent
return render_template("predictions.html", thePercent=thePercent, theDog = theDog)
补充说明:感谢大家的回复。我应该提到thePercent成功传递到了predictions.html文件中。例如,
<div class = "caption-full">
<a>I have a {{thePercent}} % chance of success</a>
</div>
返回了正确的输出
补充说明:我应该提到以下代码是有效的:
<div class="progress">
<div id = 'progressBar' class="progress-bar" role="progressbar" aria-valuenow="30" aria-valuemin="0" aria-valuemax="100" style="width: 30%;">
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script> $("#progressBar").css("width",'90%'); </script>
<span class="sr-only">{{thePercent}} Complete</span>
</div>
</div>
但是如果我尝试用{{thePercent}}替换'90%',我就会遇到错误。
我觉得问题在于我把JQuery和Jinja混在一起了。那么,如何仅使用Jinja来改变进度条呢?
3 个回答
0
我在Ruby on Rails(ror)中做过类似的事情,所以我想这应该差不多。你可以用jQuery来实现这个功能。只需要把你的百分比变量传递给类似下面的代码:
$("#progressBar").css("width",<%=thePercent%>);
我觉得你添加的方式之所以不奏效,是因为你没有正确处理它,让它能作为后端模板的一部分被渲染出来(所以应该是:{{thePercent}}
),这样在客户端渲染之前就能正确显示。
我建议你检查一下源代码,看看thePercent是否真的被当作值打印出来,还是仅仅作为文本显示。
1
好的,
我想我明白了:
<div class="progress">
<div id = 'progressBar' class="progress-bar" role="progressbar" aria-valuenow="30" aria-valuemin="0" aria-valuemax="100" style="width: 30%;">
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script> $("#progressBar").css("width","{{thePercent}}"); </script>
</div>
</div>
2
你并不是在输出 thePercent
的值,而是把 style
属性设置成了字符串 'thePercent'
。你需要用 Jinja 的 {{}}
来输出它的值,就像你在编辑中做的那样。
<div class="progress-bar progress-bar-success" style="width:{{ thePercent }}%">
编辑:
我更新了 style
属性。因为 thePercent
只包含百分比,而不是属性的完整值,所以剩下的部分(比如 width
和 %
)需要在模板中处理。