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

  • Flask Framework Cookbook
  • Shalabh Aggarwal
  • 217字
  • 2021-08-05 17:17:20

Organization of static files

Organizing static files such as JavaScript, stylesheets, images, and so on efficiently is always a matter of concern for all web frameworks.

How to do it…

Flask recommends a specific way to organize static files in our application:

my_app/
    - app.py
    - config.py
    - __init__.py
    - static/
       - css/
        - js/
        - images/
            - logo.png

While rendering them in templates (say, the logo.png file), we can refer to the static files using the following line of code:

<img src='/static/images/logo.png'>

How it works…

If there exists a folder named static at the application's root level, that is, at the same level as app.py, then Flask will automatically read the contents of the folder without any extra configuration.

There's more…

Alternatively, we can provide a parameter named static_folder to the application object while defining the application in app.py:

app = Flask(__name__, static_folder='/path/to/static/folder')

In the img src path in the How to do it… section, static refers to the value of static_url_path on the application object. This can be modified as follows:

app = Flask(
    __name__, static_url_path='/differentstatic',
    static_folder='/path/to/static/folder'
)

Now, to render the static file, we will use the following:

<img src='/differentstatic/logo.png'>

Note

It is always a good practice to use url_for to create the URLs for static files rather than explicitly define them:

<img src='{{ url_for('static', filename="logo.png") }}'>

We will see more of this in the upcoming chapters.

主站蜘蛛池模板: 阜平县| 凭祥市| 玛曲县| 禄劝| 靖边县| 周宁县| 浙江省| 饶河县| 利川市| 郑州市| 甘德县| 开鲁县| 安化县| 东辽县| 灵石县| 焦作市| 筠连县| 西安市| 衡水市| 高尔夫| 铁岭县| 普定县| 宜州市| 宁德市| 合山市| 绥德县| 南平市| 沙坪坝区| 杭锦后旗| 平泉县| 错那县| 化隆| 吉木萨尔县| 衡水市| 韩城市| 钟祥市| 平利县| 天门市| 肥乡县| 藁城市| 光山县|