首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >具有多个变量的render_template

具有多个变量的render_template
EN

Stack Overflow用户
提问于 2012-08-24 00:49:11
回答 2查看 102.7K关注 0票数 45

我使用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可以做到这一点吗?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-08-24 01:07:25

您可以向视图传递多个参数。

您可以传递所有的局部变量

@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" );

api doc

票数 77
EN

Stack Overflow用户

发布于 2019-07-01 04:56:44

还可以将列表传递给render_template的上下文变量,并在HTML中使用Jinja的语法引用其元素。

example.py

mylist = [user, content, timestamp]
return render_template('exemple.html', mylist=l)

exemple.html

...
<body>
    {% for e in mylist %}
        {{e}}
    {% endfor %}
</body>
...
票数 7
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12096522

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档