Pass variables to Flask's render_template
Asked Answered
R

4

58

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)
Reiner answered 23/8, 2012 at 16:49 Comment(0)
P
96

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())
Piggish answered 23/8, 2012 at 17:7 Comment(0)
C
25
return render_template('im.html', user= None, content = xxx, timestamp = xxx)

You can pass as many variables as you need. The api

excerpt:

flask.render_template(template_name_or_list, **context) Renders a template from the template folder with the given context.

Parameters: template_name_or_list – the name of the template to be rendered, or an iterable with template names the first one existing will be rendered context – the variables that should be available in the context of the template.

Crossway answered 23/8, 2012 at 16:55 Comment(0)
A
13

It is also possible to pass a list to render_template's context variables, and refer to its elements with Jinja's syntax in HTML.

example.py

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

example.html

...
<body>
    {% for e in mylist %}
        {{e}}
    {% endfor %}
</body>
...
Acerbic answered 30/6, 2019 at 20:56 Comment(0)
C
1

To pass variables to Flask's render_template function, you can create a dictionary containing the variables you want to pass and then provide this dictionary as keyword arguments to render_template. Here's how you can do it:

context = {
    'name': 'test',
    'age': '35'
}

render_template("index.html", **context)

In the template, you can access the variables directly:

<h1>Hello, {{ name }}!</h1>
<p>You are {{ age }} years old.</p>
Curettage answered 23/3, 2024 at 20:40 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.