釋放雙眼,帶上耳機,聽聽看~!
flask – jinja2範本範本導入在項目根目錄下創建一個templates目錄,flask會自動在這裡尋找範本如果不想把範本放在這個目錄下的話,那麼可以在初始化flask的時候指定template_folder來指定範本的路徑範本傳遞參數使用render_template渲染範本的時候可以傳遞關鍵字
flask — jinja2範本
範本導入
在項目根目錄下創建一個templates
目錄,flask會自動在這裡尋找範本
如果不想把範本放在這個目錄下的話,那麼可以在初始化flask
的時候指定template_folder
來指定範本的路徑
範本傳遞參數
使用render_template
渲染範本的時候可以傳遞關鍵字參數
到範本文件中
有三種使用關鍵字參數的方法
1. 直接添加到視圖函式中
# 省略初始化
@app.route('/template')
def template():
return render_template('index.html',foo='hello, world!')
<!-- 省略其他標籤 -->
<p>{{ foo }}</p>
- 使用字典(關鍵字參數比較多的時候)
# 省略初始化
@app.route('/template')
def template():
context={
'author':'ding',
'age':18,
'say':'hello, world!'
}
return render_template('index.html',context=context)
<!-- 省略其他標籤 -->
<p>{{context.author}}</p>
<p>{{context.age}}</p>
<p>{{context.say}}</p>
上面這種寫法不夠優雅,還可以修改成使用關鍵字參數
# 省略初始化
@app.route('/template')
def template():
context={
'author':'ding',
'age':18,
'say':'hello, world!'
}
return render_template('index.html',**context)
<!-- 省略其他標籤 -->
<p>{{author}}</p>
<p>{{age}}</p>
<p>{{say}}</p>
範本中使用url_for
在jinja2範本中使用url_for
和在視圖函式中使用是基本相同的
語法:{{url_for('視圖函式名稱',[其他參數])}}
# 省略初始化
@app.route('/')
def hello_world():
return render_template('index.html')
@app.route('/login/')
def login():
return render_template('login.html')
<!-- 省略其他標籤 -->
<!-- index.html -->
<a href="{{ url_for('login') }}">click me</a>
聲明:本文為原創作品,版權歸作者所有。未經許可,不得轉載或用於任何商業用途。如若本站內容侵犯了原著者的合法權益,可聯繫我們進行處理。