2

I was reading up on Flask's render_template() when I came across this block of code:

@app.route('/result',methods = ['POST', 'GET'])
def result():
  if request.method == 'POST':
     result = request.form
     return render_template("result.html",result = result)

Why do we have to write result=result when passing input to render_template()? It just seems more cumbersome when you could put

return render_template("result.html", result)

Is there a reason why Flask presents this method like so?

Wannabe
  • 101
  • 1
  • 9

1 Answers1

4

The reason behind this is that your template file can have a lot of placeholders and it needs to know how to distinguish between all of them.

For example, you could have the following template:

<!DOCTYPE html>
<html lang="en">
<head>
    <title> {{ page_title }}
</head>
<body>
    {{ page_body }}
</body>
</html>

Now think that you wouldn't have the names for the variables, how does the function that needs to render the page and inject the variables instead of the placeholders would know where to place each variable? That's why you are actually passing a dictionary in the form of key=value and you can pass multiple keys and values to the function without being restricted about the number of parameters the function knows to expect.

In the above example, the call to the render_template function would be:

render_template('page.html', page_title='this is my title', page_body='this is my body')

This is the actual signature of the function (taken from here):

def render_template(template_name_or_list, **context):
    """Renders a template from the template folder with the given
    context.
    :param 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
    :param context: the variables that should be available in the
                    context of the template.
    """

The **context is the way of Python to aggregate all the key=value parameters passed to the function and have them as a dictionary in the form of:

{'key1': value1, 'key2': value2, ...}

And I guess either the function itself or the subfunctions being called are interpreting the template page and looks for the variable name you provided in the template with the value from the dictionary that corresponds to the key which is the variable name.

Long story short, that way the function is generic enough for everyone to pass as many parameters as they would like and for the function to be able to render the template page correctly.

Avihoo Mamka
  • 4,656
  • 3
  • 31
  • 44