The function of the filter (essentially a function, used in the template) is to calculate and format the data. The syntax format of the filter: {{variable|filter}}
#coding=utf-8
from flask import Flask,render_template #render_template 位模板
app = Flask(__name__)
@app.route('/')
def hello_world():
return render_template('index.html') #index.html file is in the same level folder static
if __name__=='__main__':
app.run(debug=True)
Enter 127.0.0.1:5000/index.html in the browser and the content of index.html appears on the page
####Custom filter, define function in view
#coding=utf-8
from flask import Flask,render_template
app = Flask(__name__)
@app.route('/')
def hello_world():
return render_template('index.html')
# Custom filter, define function in view function
def double_filter(ls):
return ls[: :-2]
#Add a custom filter to the template, the first parameter is the function name, and the second parameter is the custom filter name
app.add_template_filter(double_filter,'db2')
# In this way, the filter db2 can be used in the index.html file <p>{{'abcdefg' | db2}}</p>
#Custom filter 2, if the custom filter and the built-in filter have the same name, the built-in filter will be overwritten, that is, the meaning of the previous filter will be changed
“”“
<p>{{'abcdefg' | reverse}}</p>Under normal circumstances, reverse the string and manually define the reverse filter of the same name, then the reverse filter is a custom meaning
”“”
@app.template_filter(db3)
def double_filter(ls):
return ls[: :-3]
# In this way, the filter db3 can be used in the index.html file <p>{{'abcdefg' | db3}}</p>
if __name__=='__main__':
app.run(debug=True)