flask-study-003

本篇博客記錄flask使用的jinja2模板使用方法

1. 模板的基本使用

app.py如下:

from flask import Flask, render_template, redirect

app = Flask(__name__)
app.config['DEBUG'] = True

@app.route('/')
def index():
    name = "liwl"
    return render_template('index.html', name=name)

@app.route('/index')
def newindex():
    return redirect('/')

@app.route('/user/<name>')
def user(name):
    return f"hello,{name}"

if __name__ == "__main__":
        app.run()

templates/index.html如下:

<h1>
{% for i in range(10) %}
hello, I am {{ name }}
<br>
{% endfor %}
</h1>

index.html裏面的name是佔位符號,通過{{ name }} 來佔位

語句通過:{% %}來表示,同時需要 {% endfor %}結束

{% for %}{% endfor %},{% if %}{% else %}

<h1>
hello, I{% if name %} am {{ name }}{% else %},stranger{% endif %}
</h1>

2. 基本語法

2.1 變量

{{ name }}結構表示一個變量,是一種特殊的佔位符。{{ }}符號內部的字符串是python對象,由render_template函數的參數指定。

jinja2能夠識別所有類型的變量,包括列表,字典,對象。

變量的值,可以通過過濾器修改。比如hello,{{ name | capitalize }},將name的首字母大寫。

2.2 控制結構

條件語句

{% if xxx %}
	xxx
{% else %}
	xxx
{% endif %}

循環語句

{% for xxx in xxx %}
	xx
{% endfor %}

2.3 宏

類似於python函數。把宏定義在macros.html,在其他需要宏的html中,通過{% import 'macros.html' as macros %}

比如定義一個宏

{% macro render_comment(comment) %}
	<li>{{ comment }}</li>
{% endmacro %}

本文件使用宏:

<ul>
    {% for comment in comments %}
    	{{ render_comment(comment)}}
    {%endfor%}
</ul>

其他文件使用宏:

{% import 'macros.html' as macros %}
<ul>
    {% for comment in comments %}
    	{{macros.render_commnet(comment)}}
    {% endfor %}
</ul>

2.4 模板的複用

方式一:{% include 'common.html' %},這種方式能夠使用common.html裏面定義的內容

方式二:{% extends 'base.html' %},這種方式繼承了base.html內容

extends繼承的base.html,3個區塊被重新定義。衍生模板同名區塊覆蓋基模板的同名區塊。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章