官术网_书友最值得收藏!

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

主站蜘蛛池模板: 逊克县| 盐边县| 石首市| 肇庆市| 密山市| 郁南县| 大宁县| 锦屏县| 乌鲁木齐市| 噶尔县| 吉林省| 琼海市| 海阳市| 油尖旺区| 鄂州市| 桂阳县| 巩留县| 江城| 诸暨市| 镇江市| 菏泽市| 登封市| 闵行区| 九江县| 孟津县| 东乌珠穆沁旗| 专栏| 客服| 巩义市| 应用必备| 镇康县| 张家川| 河池市| 蕉岭县| 无为县| 朝阳市| 库车县| 宿松县| 平武县| 沈阳市| 宁远县|