Bootstrap layout

Most of the applications in Flask follow a specific pattern to lay out templates. In this recipe, we will talk about the recommended way of structuring the layout of templates in a Flask application.

Getting ready

By default, Flask expects the templates to be placed inside a folder named templates at the application root level. If this folder is present, then Flask will automatically read the contents by making the contents of this folder available for use with the render_template() method, which we will use extensively throughout this book.

How to do it…

Let's demonstrate this with a small application. This application is very similar to the one we developed in Chapter 1, Flask Configurations. The first thing to do is add a new folder named templates under my_app. The application structure will now look like the following lines of code:

flask_app/
    - run.py
    my_app/
        – __init__.py
        - hello/
            - __init__.py
            - views.py
        - templates

We need to make some changes to the application. The hello_world method in the views file, my_app/hello/views.py, will look like the following lines of code:

from flask import render_template, request

@hello.route('/')
@hello.route('/hello')
def hello_world():
    user = request.args.get('user', 'Shalabh')
    return render_template('index.html', user=user)

In the preceding method, we look for a URL query argument, user. If it is found, we use it, and if not, we use the default argument, Shalabh. Then, this value is passed to the context of the template to be rendered, that is, index.html, and the resulting template is rendered.

To start with, the my_app/templates/index.html template can be simply put as:

<html>
  <head>
    <title>Flask Framework Cookbook</title>
  </head>
  <body>
    <h1>Hello {{ user }}!</h1>
    <p>Welcome to the world of Flask!</p>
  </body>
</html>

How it works…

Now, if we open the URL, http://127.0.0.1:5000/hello, in a browser, we will see a response, as shown in the following screenshot:

We can also pass a URL argument with the user key as http://127.0.0.1:5000/hello?user=John; we will see the following response:

As we can see in views.py, the argument passed in the URL is fetched from the request object using request.args.get('user') and passed to the context of the template being rendered using render_template. The argument is then parsed using the Jinja2 placeholder, {{ user }}, to fetch the contents from the current value of the user variable from the template context. This placeholder evaluates all the expressions that are placed inside it, depending on the template context.

See also