I want to pass multiple variables from my Flask view to my Jinja template. Right now, I can only pass one. How do I pass multiple variable when rendering a template?
@app.route("/user/<user_id>/post/<post_id>", methods=["GET", "POST"]) def im_research(user_id, post_id): user = mongo.db.Users.find_one_or_404({'ticker': user_id}) return render_template('post.html', user=user)
Advertisement
Answer
The render_template
function takes any number of keyword arguments. Query for each of the things you need in the template, then pass the results of each query as another argument to render_template
.
@app.route("/user/<user_id>/post/<post_id>") def im_research(user_id, post_id): user = get_user_by_id(id) post = get_user_post_by_id(user, id) return render_template("post.html", user=user, post=post)
Python also has a built-in locals()
function that will return a dict of all locally defined variables. This is not recommended as it may pass too much and obscures what specifically is being passed.
@app.route("/user/<user_id>/post/<post_id>") def im_research(user_id, post_id): user = get_user_by_id(id) post = get_user_post_by_id(user, id) return render_template("post.html", **locals())