Python

「Flask筆記」 jinja2範本總結

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>
  1. 使用字典(關鍵字參數比較多的時候)
# 省略初始化
@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>

Recent Posts

2023 年 WordPress 中最棒的多語言翻譯外掛推薦

擔心如何翻譯您的網站語言以支持…

12月 ago

2023 年 WordPress 中最棒的可視化頁面構建器外掛推薦

在設計任何頁面或網站時,對於不…

12月 ago

Ella 多用途 Shopify 佈景主題

Shopify 佈景主題市場上有許…

12月 ago

AI Engine Pro

喵容今天帶來的 AI Engi…

12月 ago

AIKit

喵容今天為您帶來 AIKit …

12月 ago

AIomatic

喵容今天為您帶來AIOmati…

12月 ago