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个区块被重新定义。衍生模板同名区块覆盖基模板的同名区块。

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