示例:使用Flask和Jinja传递test
以在模板中打印它。
@app.route('/mypage')
def mypage():
# just open the json file and read it...
input_file = file(FILE, "r")
j = json.loads(input_file.read().decode("utf-8-sig"))
for item in j[:]:
test = "test"
return render_template('mypage.html', j=j, test = test, config = {'environment_args':{'autoescape':False}})
注意j[:]
现在当我想在HTML文件中打印它时:
<p>{{test}}</p>
结果是:
None
更新:这是json文件的示例:
[
{
"trailers": {
"quicktime": [],
"youtube": [
{
"source": "FZCxSiYRh7Q",
"type": "Trailer",
"name": "Trailer 1",
"size": "Standard"
}
],
"id": 54315
},
"date": "2008",
"genres": [
{
"id": 18,
"name": "Drame"
}
],
"tagline": "",
"popularity": 0.23,
"vote_count": 2,
"start": "Monday 09 December 01:10",
"length": "95",
"overview": "",
"vote_average": 10.0,
},
{etc}
]
答案 0 :(得分:0)
您显示的JSON似乎有错误 - 最后一个数字后面的逗号。以下是一个适合我的例子:
#app.py
from flask import Flask, render_template, json
app = Flask(__name__)
@app.route('/')
def mypage():
# just open the json file and read it...
input_file = file('file.json', "r")
j = json.loads(input_file.read().decode("utf-8-sig"))
for item in j[:]:
print item
test = "test"
return render_template('index.html', j=j, test=test, config={'environment_args': {'autoescape': False}})
if __name__ == '__main__':
app.run(debug=True)
示例HTML模板,渲染测试变量,并迭代JSON结构以打印每个开始日期:
<!-- index.html -->
<html>
<body>
{{ test }}
{% for row in j %}
<li>{{ row.start }}</li>
{% endfor %}
</body>
</html>
只是为了完整性 - 我使用的JSON文件。
[
{
"trailers": {
"quicktime": [],
"youtube": [
{
"source": "FZCxSiYRh7Q",
"type": "Trailer",
"name": "Trailer 1",
"size": "Standard"
}
],
"id": 54315
},
"date": "2008",
"genres": [
{
"id": 18,
"name": "Drame"
}
],
"tagline": "",
"popularity": 0.23,
"vote_count": 2,
"start": "Monday 09 December 01:10",
"length": "95",
"overview": "",
"vote_average": 10.0
}
]