IT, Programming, & Web Development › Forums › CS50’s Introduction to Computer Science by Harvard University on Edx › Week 9: Flask › Understanding Flask routing and template rendering with query parameters
- This topic is empty.
-
AuthorPosts
-
April 13, 2024 at 9:36 am #2279
[dm_code_snippet background=”yes” background-mobile=”yes” slim=”no” line-numbers=”no” bg-color=”#abb8c3″ theme=”dark” language=”markup” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]
@app.route("/") def index(): name = request.args["name"] return render_template("index.html", placeholder=name)
[/dm_code_snippet]
While I could perhaps understand that on the third line of the above code, name is a newly defined variable, not sure about [“name”] as part of request.args[“name”]. Does [“name”] refers to the name of a key named “name” that when will be put on the browser url after ? will lead to storing of the value of the key in a Python dictionary?
So how does it relate to placeholder=name in the fourth and the last line? Whatever entered as part of {{placeholder}} in index.html gets allocated to name variable of the 3rd line that will next consider the same as value of the key named [“name”]?
ChatGPT:
Yes, you’re on the right track! Let’s break it down:
request.args
is a dictionary-like object in Flask that contains the parsed contents of the query string in the URL. So, when you accessrequest.args["name"]
, you’re indeed retrieving the value associated with the key “name” in the query string of the URL.-
In the URL, parameters are usually passed in the format
?key1=value1&key2=value2
. For example, if your URL ishttp://example.com/?name=John`, then
request.args[“name”]` would return “John”. -
Now, let’s look at the
render_template
function. In Flask, this function is used to render HTML templates. When you callrender_template("index.html", placeholder=name)
, you’re telling Flask to render the “index.html” template and pass the value of thename
variable to it, which will be available in the template as{{ placeholder }}
. -
In the “index.html” template, wherever you have
{{ placeholder }}
, it will be replaced with the value of thename
variable. So, ifname
is “John”, then{{ placeholder }}
will be “John”.
So, essentially, whatever value is passed in the “name” parameter of the URL will be displayed in the HTML template at the placeholder position.
-
AuthorPosts
- You must be logged in to reply to this topic.