您当前的位置: 首页 >  flask
  • 0浏览

    0关注

    214博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

Flask(3):Flask的模板templates

不愿透露姓名の网友 发布时间:2020-08-03 21:04:02 ,浏览量:0

文章目录
  • 1.前端使用后端的值
  • 2.后端给前端传入标签
  • 3.for和if用法
  • 4.模板继承

1.前端使用后端的值

demo.py文件代码

from flask import Flask, render_template, request, redirect

app = Flask(__name__, template_folder='templates')

@app.route('/index/')
def index():
    content = {
        'k1': 2,
        'k2': [1, 2, 3],
        'k3': {'name': '张三', 'age': 15},
        'k4':lambda x:x+1
    }
    return render_template('index.html', **content)


if __name__ == '__main__':
    app.run(debug=True)

index.html文件,在我们flask的模板语法中,更贴近原始python代码的取值


    取单个字符:{{k1}}
    取列表的值:{{k2.0}},{{k2[0]}}
    取字典的值:{{k3.name}},{{k3['name']}},{{k3.get('name','空')}}
    
    不传参数的值:{{k4}}
    不传参数的值:{{k4(100)}}

运行

在这里插入图片描述

2.后端给前端传入标签

demo.py,定义一个添加input标签的函数

from flask import Flask, render_template, request, redirect

app = Flask(__name__, template_folder='templates')

def add_input():
    return ''

@app.route('/index/')
def index():
    content = {'k1':add_input}
    return render_template('index.html', **content)

if __name__ == '__main__':
    app.run(debug=True)

index.html


    {{k1()}}

运行

在这里插入图片描述

此处是xss----->>介绍,因此解决方式有两种:

第一种:前端对此段代码标注安全


    {{k1()|safe}}

第二种:后端使用Markup模块

from flask import Flask, render_template, Markup

app = Flask(__name__, template_folder='templates')

def add_input():
    return Markup('')

@app.route('/index/')
def index():
    content = {'k1':add_input}
    return render_template('index.html', **content)

if __name__ == '__main__':
    app.run(debug=True)

在这里插入图片描述

3.for和if用法

py文件

@app.route('/index/')
def index():
    content = {
        'k2': [1, 2, 3],
        'k3': {'name': '张三', 'age': 15},
    }
    return render_template('index.html', **content)

html文件


    遍历列表
    {% for i in k2 %}
    	{% if i >= 2 %}
    		{{i}}
    	{% else %}
    		xxxx
    	{% endif %}
    {% endfor %}
    
    遍历字典
    {% for i in k3 %}
   	 	{{i}}
    {% endfor %}
    
     {% for k in k3.keys() %}
    	{{k}}
    {% endfor %}
     
    {% for v in k3.values() %}
    	{{v}}
    {% endfor %}
     
    {% for k,v in k3.items() %}
   		 {{k}}:{{v}}
    {% endfor %}

在这里插入图片描述

4.模板继承

py文件

from flask import Flask, render_template, Markup

app = Flask(__name__, template_folder='templates')


@app.route('/index/')
def index():
    return render_template('index.html')

@app.route('/login/')
def login():
    return render_template('login.html')

if __name__ == '__main__':
    app.run(debug=True)

index.html




    
    主页


头部
{% block content %}{% endblock %}


login.html

{% extends 'index.html' %}
{% block content %}
我是内容
{% endblock %}

运行,进入login.html,发现继承了index.html的内容

在这里插入图片描述

关注
打赏
1657102503
查看更多评论
立即登录/注册

微信扫码登录

0.0962s