flask渲染jinja2模板和傳參:
1、如何渲染模板:
模板放在“template”文件夾下。
從flask導入render_template函數。
在視圖函數中,使用“render_template”。
2、模板傳參:
如果只有一個或少量參數,直接在render_template函數中添加關鍵字參數就可以了。
如果有多個參數時,那么可以把所有參數放在字典中,然后在render_template函數中使用**兩個星號,把字典轉換成關鍵字參數傳遞進去,這樣的代碼更方便管理和使用。
3、在模板中如果要使用一個變量,語法是{{params}}
4、訪問模型中的屬性或字典,可以通過{{params.property}}的形式,或者采用{{params[property]}}
代碼示例
from flask import Flask,redirect,url_for,render_template
@app.route('/index')
def index():
#通過字典傳參
class Person():
name='黃興'
age=20
context={
'sex':'man',
'age':'18',
'name':'lianghao'
'website':{
'baidu':'www.baidu.com',
'淘寶':'www.taobao.com'
}
}
return render_template('index.html',**context)
模板:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
大家好!我是{{person.name}},我的年齡是{{ person.age }},我的性別是{{ sex }},喜歡{{website.baidu}},不喜歡{{ website['淘寶'] }}
</body>
</html>
if判斷
1、語法示例:
@app.route('/ifstatement/<number>/')
def ifstatement(number):
context = {
'username': 'lianghao',
'city': 'fuqing',
'age': 18
}
if number=='1':
return render_template('if_statement.html', context=context)
else:return '測試'
模板:
{% if context and context.age>17 %}
<a href="#">姓名:{{ context.username }}</a>
<a href="#">城市:{{context.city }}</a>
{% else %}
<a href="#">test</a>
{% endif %}
for循環遍歷列表和字典
context = {
'username': 'lianghao',
'city': 'fuqing',
'age': 18
}
name=['tom','jack','snack','james']
模板:
{% endif %}
{% for k in context %}
{{ k }}{{ context[k] }}
{% endfor %}
{% for i in name %}
{{ i }}
{% endfor %}
過濾器
1、介紹
過濾器可以處理變量,把原始的變量經過處理后再展示出來,作用的對象是變量
default過濾器:如果當前變量不存在,可以指定默認值
2、代碼示例
變量woerver,但不傳入模板中,再模板中使用default過濾器
列表name,導入模板,但在模板中使用name[5],使得default過濾器生效
@app.route('/ifstatement/<number>/')
def ifstatement(number):
context = {
'username': 'lianghao',
'city': 'fuqing',
'age': 18
}
woerwer='1234'
name=['tom','jack','snack','james']
if number=='1':
return render_template('if_statement.html', context=context,name=name)
else:return '測試'
模板:
{{ name[5]|default('dadadaaada') }}
{{ woerwer|default('35',false) }}
繼承和block
1、繼承的作用和語法
繼承可以把一些公共的代碼放在父模板中,避免每個模板寫同樣的代碼
語法:
{%extends 'base.html'%}
2、block的實現
作用:可以讓子模板實現一些自己的需求,父模板需要提前定義好。
注意點:子模板的代碼,必須放在block塊中
父模板:
<%block xxxx%>
<%endblock%>
子模板:
<%block xxxx%>
<%endblock%>
URL鏈接
使用url_for('')反轉
<a href="{{ url_for('index') }}">登錄</a>
加載靜態文件
語法:
url_for('static',filename='路徑')
從static文件夾開始尋找,可以加載CSS、JS、IMAGE文件
<link rel="stylesheet"href="{{ url_for('static',filename='css/login.css') }}">加載CSS文件
<p>)</p>加載圖片
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="{{ url_for('static',filename='js/index.js') }}"></script>加載JS腳本
</head>