靜態(tài)文件
動態(tài)的 web 應用同樣需要靜態(tài)文件。CSS 和 JavaScript 文件通常來源于此酬姆。理想情況下鲸拥, 你的 web 服務器已經(jīng)配置好為它們服務仑乌,然而在開發(fā)過程中 Flask 能夠做到绅喉。 只要在你的包中或模塊旁邊創(chuàng)建一個名為 static 的文件夾足陨,在應用中使用 /static 即可訪問缩焦。
給靜態(tài)文件生成 URL 读虏,使用特殊的 'static' 端點名:url_for('static', filename='style.css'),這個文件應該存儲在文件系統(tǒng)上稱為 static/style.css袁滥。
模板
jinjia2為了防止跨站點腳本攻擊盖桥,出于安全考慮將參數(shù)值作為字符串,例如:
app.py
def hello_world():
return render_template('index.html', title='<h1>Welcome!</h1>')
index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="{{ url_for('static',filename='site.css') }}">
</head>
<body>
{{ title }}
<a href="{{ url_for('.services') }}">services</a>
<a href="{{ url_for('.about') }}">about</a>
</body>
</html>
Paste_Image.png
如果要顯示正常結(jié)果题翻,需做如下修改:
{% autoescape false %}
{{ title }}
{% endautoescape %}
或者:
{{ title|safe }}
則結(jié)果顯示為:
Paste_Image.png
第二種方法就是Flask的Jinja2模板引擎 — 過濾器,也可以自定義markdown過濾器:
demo01.py
@app.template_filter('md')
def markdown_to_html(txt):
from markdown import markdown
return markdown(txt)
@app.route('/')
def index():
response = make_response(render_template('index.html', title='<h1>Welcome!</h1>',body = '##header2'))
index.html
···
{{ body | md | safe }}
···
模板的繼承--包含和宏
在模板中定義好html的格式揩徊,在子頁面中重寫