一、前言
參考https://www.cnblogs.com/poloyy/p/14999797.html
沒有前端基礎,看的有些些複雜,只瞭解簡單用法就行,後面做網站如果是用到這模板的話再深入學習吧。
二、目錄結構
一般來說 templates 就是存放模板的目錄,如果遇到下面的報錯,要注意下目錄結構:
jinja2.exceptions.TemplateNotFound: index.html
三、實戰示例一
1、jinja2 模板代碼
<!DOCTYPE html> <html> <body> <h2>My name is {{ name }}, I am {{ age }} years old</h2> </body> </html>
2、flask 代碼
- 首先,需要 import render_template
- 然後,視圖函數調用 render_template,對模板 templates/index.html 進行渲染
- render_template 包含有 2 個命名參數:name 和 age,模板引擎將模板 templates/index.html 中的變量進行替換
from flask import Flask, render_template app = Flask(__name__) @app.route('/') def index(): return render_template('index.html', name='tom', age=10) app.run(debug=True)
瀏覽器運行效果:
四、實戰示例二
1、分界符
jinja2 模板文件混合 html 語法與 jinja2 語法,使用分界符區分 html 語法與 jinja2 語法。有 5 種常見的分界符:
- {{ 變量 }},將變量放置在 {{ 和 }} 之間;
- {% 語句 %},將語句放置在 {% 和 %} 之間;
- {# 註釋 #},將註釋放置在 {# 和 #} 之間;
- ## 註釋,將註釋放置在 # 之後
2、變量 語法
jinjia2模板中,使用{{var}}包圍的標識符稱爲變量,模板渲染會將其替換爲python中的變量,語法如下:{{ 變量 }}
3、jinjia2模板
包含有 3 種類型的變量:字符串、列表、字典,它們會被替換爲同名的 Python 變量
<html> {{ string }} <ul> <li> {{ list[0] }} <li> {{ list[1] }} <li> {{ list[2] }} <li> {{ list[3] }} </ul> <ul> <li> {{ dict['name'] }} <li> {{ dict['age'] }} </ul> </html>
4、flask代碼
from flask import Flask, render_template app = Flask(__name__) string = 'www.imooc.com' list = ['www', 123, (1, 2, 3), {"name": "zhangsan"}] dict = {'name': 'zhangsan', 'age': True} @app.route('/2') def index2(): return render_template('index2.html', string=string, list=list, dict=dict) app.run(debug=True)
列表的值包含字符串、數字、元組、字典,字典的值包含字符串、布爾值。
瀏覽器運行的效果: