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代码的取值
<ul>
<h1>取单个字符:{
{k1}}</h1>
<h1>取列表的值:{
{k2.0}},{
{k2[0]}}</h1>
<h1>取字典的值:{
{k3.name}},{
{k3['name']}},{
{k3.get('name','空')}}</h1>
<h1>不传参数的值:{
{k4}}</h1>
<h1>不传参数的值:{
{k4(100)}}</h1>
</ul>
运行
2.后端给前端传入标签
demo.py,定义一个添加input标签的函数
from flask import Flask, render_template, request, redirect
app = Flask(__name__, template_folder='templates')
def add_input():
return '<input value="张三" />'
@app.route('/index/')
def index():
content = {
'k1':add_input}
return render_template('index.html', **content)
if __name__ == '__main__':
app.run(debug=True)
index.html
<ul>
<h1>{
{k1()}}</h1>
</ul>
运行
此处是xss----->>介绍,因此解决方式有两种:
扫描二维码关注公众号,回复:
13170918 查看本文章

第一种:前端对此段代码标注安全
<ul>
<h1>{
{k1()|safe}}</h1>
</ul>
第二种:后端使用Markup模块
from flask import Flask, render_template, Markup
app = Flask(__name__, template_folder='templates')
def add_input():
return Markup('<input value="张三" />')
@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文件
<ul>
<h1>遍历列表</h1>
{% for i in k2 %}
{% if i >= 2 %}
<li>{
{i}}</li>
{% else %}
<li>xxxx</li>
{% endif %}
{% endfor %}
<h1>遍历字典</h1>
{% for i in k3 %}
<li>{
{i}}</li>
{% endfor %}
{% for k in k3.keys() %}
<li>{
{k}}</li>
{% endfor %}
{% for v in k3.values() %}
<li>{
{v}}</li>
{% endfor %}
{% for k,v in k3.items() %}
<li>{
{k}}:{
{v}}</li>
{% endfor %}
</ul>
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>主页</title>
</head>
<body>
<div>头部</div>
{% block content %}{% endblock %}
</body>
</html>
login.html
{% extends 'index.html' %}
{% block content %}
<h1>我是内容</h1>
{% endblock %}
运行,进入login.html,发现继承了index.html的内容