[英]Flask: passing multiple python based variables through render_template()
[英]render_template with multiple variables
我使用 Flask(作为框架)和 MongoDB(作为数据库服务器)。 现在,我所能做的就是传递我从数据库中获得的一个参数:
@app.route('/im/', methods=['GET', 'POST'])
def im_research(user=None):
error = None
if request.method == 'POST':
if request.form['user']:
user = mongo.db.Users.find_one_or_404({'ticker':request.form['user']})
return redirect(url_for('im_user',user= user) )
else:
flash('Enter a different user')
return redirect(url_for('im'))
if request.method == 'GET':
return render_template('im.html', user= None)
我如何从数据库中传递多个变量:例如:在我的 Mongo 数据库中:我的数据库中有这些东西,我想将它们全部传递给我的模板。
{
users:'xxx'
content:'xxx'
timestamp:'xxx'
}
是否可以通过使用 Flask 来做到这一点?
您可以将多个参数传递给视图。
您可以传递所有局部变量
@app.route('/')
def index():
content = """
teste
"""
user = "Hero"
return render_template('index.html', **locals())
或者只是传递你的数据
def index() :
return render_template('index.html', obj = "object", data = "a223jsd" );
return render_template('im.html', user= None, content = xxx, timestamp = xxx)
您可以根据需要传递任意数量的变量。 api
摘抄:
flask.render_template(template_name_or_list, **context) 使用给定的上下文渲染模板文件夹中的模板。
参数: template_name_or_list - 要呈现的模板的名称,或具有模板名称的可迭代对象,第一个存在的模板将被呈现 context - 模板上下文中应该可用的变量。
也可以将列表传递给 render_template 的上下文变量,并在 HTML 中使用 Jinja 的语法引用其元素。
例子.py
l = [user, content, timestamp]
return render_template('exemple.html', l=l)
例子.html
...
<body>
{% for e in l %}
{{e}}
{% endfor %}
</body>
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.