python_note
  • Introduction
  • My Python
    • Anaconda
    • argparse
    • datetime
    • json
    • logging
    • numpy
    • open
    • openCC
    • pandas & csv
    • Socket & SocketServer
    • re
    • yaml
    • smtp
    • 物件操作
    • unittest
    • 線程
    • prettytable
    • IO
    • pycurl
    • sys
    • pickle
    • auto-python-to-exe
    • cython
    • nuitka
  • Crawler
    • Urllib & Requests
      • User-agent
      • Percent-Encoding
      • mail code
    • Selenium
    • TCP & UDP
    • 控制字符(control character)
  • Web Development
    • Flask
      • RESTful api
      • Template
      • blueprint
    • Django
      • 環境佈署(windows)
    • 檢查Port
    • Apache
    • 使用者行為
    • jQuery
    • 壓力測試
    • DataTable
    • Bootstrap
    • CSS
    • JavaScript
    • Chart.js
  • Deep Learning
    • Keras 設定
    • RNN
    • LSTM
  • Test
    • T-Test
  • 資料結構
    • Hash
    • 時間複雜度
  • NLP
    • N-gram
    • CKIP
    • 中文轉數字
    • CRF
    • Mutual Information
    • 模糊比對
  • Linebot
    • Heroku
    • 圖文選單
    • channel
  • Linux
    • 常用指令
    • shell script
    • sshfs
    • ssh
    • nodejs & npm
    • debug
  • GCP
    • app engine
    • ssh(gcp)
    • gsutil
    • brabrabra
    • Load Balancer
    • k8s
  • Database
    • mysql
    • elasticsearch
      • Query
      • Backup and Restore
      • elasticdump
      • es2csv
      • ELK
    • mongodb
      • install
      • authentication
      • pymongo
    • sql server
  • go
    • Swarm
  • Docker
    • Kitematic
    • Dockerfile
    • Swarm
  • Git
  • 其他
    • USB軟體保護
    • Windows效能監視器
  • Blockchain
Powered by GitBook
On this page
  • Template
  • 動態變數
  • 判斷式
  • 迴圈
  • Macro
  • import
  • include
  • set
  • with

Was this helpful?

  1. Web Development
  2. Flask

Template

Template

自動更新 app.config['TEMPLATES_AUTO_RELOAD'] = True

動態變數

動態網頁操作上與django相似

# 單一變數
<h1>hello, {{ name }}! </h1>


# 迴圈
<ul>
    {% for comment in comments %}
        <li>{{ comment }}</li>
    {% endfor %}
</ul>

在flask中將變數傳送至template

# python3
@app.route('/hihi',methods = ['post'])  
def test_function():  
    name = 'strawberry'
    comments = ['1', '2', '3']
    # 把所有變數加入render_template
    return render_template('signForm.html', name=name, comments=comments)

將html以變數方式傳送至template

# 可避免轉碼情況發生
{{ 變數名稱|safe }}

判斷式

和在python使用方式差不多,可使用<>、and or not之類的

{% if kenny.sick %}
   Kenny is sick.
{% elif kenny.dead %}
   You killed Kenny!  You bastard!!!
{% else %}
   Kenny looks okay --- so far
{% endif %}

迴圈

遍歷字典

{% for key, value in my_dict.items() %}
    <dt>{{ key }}</dt>
    <dd>{{ value }}</dd>
{% endfor %}

可使用else,當遍歷的參數為空或None。無法使用continue和break

{% for user in users %}
    <li>{{ user.username }}</li>
{% else %}
    <li><em>no users found</em></li>
{% endfor %}

迴圈有些自帶的變數可以使用:

loop.index 循环迭代计数(从1开始)

loop.index0 循环迭代计数(从0开始)

loop.revindex 循环迭代倒序计数(从len开始,到1结束)

loop.revindex0 循环迭代倒序计数(从len-1开始,到0结束)

loop.first 是否为循环的第一个元素

loop.last 是否为循环的最后一个元素

loop.length 循环序列中元素的个数

loop.cycle 在给定的序列中轮循,如上例在”odd”和”even”两个值间轮循

loop.depth 当前循环在递归中的层级(从1开始)

loop.depth0 当前循环在递归中的层级(从0开始)

使用方式

{% for book in books %}
    <p>{{ loop.first }}</p>
    <p>{{ loop.index }}</p>
    <p>{{ book }}</p>
{% endfor %}

Macro

類似在html使用function,方便又整齊,可以傳遞參數,但是不能有返回值

先定義input函式

{% macro input(name, value='', type='text') %}
    <input type="{{ type }}" name="{{ name }}" value="{{ value }}">
{% endmacro %}

使用時

<p>{{ input('username') }}</p>
<p>{{ input('password', type='password') }}</p>

import

可將macro內容用.html儲存,其他html可用import方式讀取並使用macro

{% import 'macro.html' as macro  %}
<tr>
    <td>用戶名:</td>
    <td>{{ macro.input('username') }}</td>
</tr>

或者

{% from "macro.html" import input %}
<tr>
    <td>密碼:</td>
    <td>{{ input("password",type="password") }}</td>
</tr>

include

將重複性高的html另外儲存,再用include讀取,就不用一直複製貼上相同的html惹

{% include 'header.html' %}
...
{% include 'footer.html' %}

set

在html文件上宣告變數來使用

{% set name='dog' %}
{% set navigation = [('index.html', 'Index'), ('about.html', 'About')] %}

這樣就可以使用和惹

with

可以用來限制set變數的效果範圍

{% with %}
    {% set foo = 42 %}
{% endwith %}
或者
{% with foo = 42 %}
    {{ foo }}
{% endwith %}

參考資料:

PreviousRESTful apiNextblueprint

Last updated 5 years ago

Was this helpful?

參考連結:

https://blog.csdn.net/lanchunhui/article/details/51570408
https://blog.csdn.net/three_co/article/details/78420213
https://stackoverflow.com/questions/3206344/passing-html-to-template-using-flask-jinja2
https://www.twblogs.net/a/5e9d77f96052e105765a65b4
flask Jinja2模版過濾器和控制語句 - 台部落
Logo
Flask中Jinja2模板引擎详解(六)–块和宏 - 思诚之道