Flask -- 静态文件 和 模板渲染


静态文件

一般用于存放图片,样式文件(css, js等)

保存位置:包中或者文件所在目录创建一个 static 目录

访问:在应用中使用 /static/...即可访问 , 更好的方式是使用url_for方法

  例如  <link rel="stylesheet" type="text/css" href="/static/css/style.css"> 

       <img src="/static/images/01.jpg"> 


模板渲染 

模板引擎:Jinja2

保存位置:应用是个模块,这个文件夹应该与模块同级;

     如果它是一个包,那么这个文件夹作为包的子目录:  

/application.py
/templates
    /hello.html

/application
    /__init__.py
    /templates
        /hello.html

例子:

from flask import render_template

@app.route('/hello/')
@app.route('/hello/<name>')
def hello(name=None):
    return render_template('hello.html', name=name)
<!doctype html>
<title>Hello from Flask</title>
{% if name %}
  <h1>Hello {{ name }}!</h1>
{% else %}
  <h1>Hello World!</h1>
{% endif %}

  

KEEP LEARNING!
原文地址:https://www.cnblogs.com/roronoa-sqd/p/4922273.html