文章目录
1.前端使用后端的值
- 1.前端使用后端的值
- 2.后端给前端传入标签
- 3.for和if用法
- 4.模板继承
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)}}
运行
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)
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 %}
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的内容