I. Overview
Flask is a lightweight Python web framework with support for the Jinja2 template engine.Jinja2 is a popular Python template engine that can be used to create dynamic web applications using Flask.
Web pages generally require html, css, and js, and may be written this way at the very beginning of learning python web:
from flask import Flask app = Flask(__name__) @('/') def hello(): return '<h1>hello</h1><p style="color:red">hello world!!!</p>' if __name__ == '__main__': (host='0.0.0.0', port=8000, debug=True)
Although the above code can also be executed, but not beautiful, now programming is basically front-end and back-end separation, will not be embedded in the back-end agent of the front-end code, in order to achieve front-end and back-end separation, the use of MVT design solutions:
M
full spelling isModel
, which has the same function as M in MVC, is responsible for interacting with the database for data processing.
V
full spelling isView
The MVC is the same as the C function in MVC, which receives requests, performs business processing, and returns an answer.
T
full spelling isTemplate
The V is the same as the V in MVC, and is responsible for encapsulating the html to be returned.
II. JinJa2 Syntax Introduction and Examples
JinJa2 Syntax Introduction and Example Explanation:
1) Variables
In Jinja2, using the{{ }}
to include a variable. In Flask, variables can be displayed by passing them to a template. The sample code is as follows:
# # Passing variables to templates in Flask from flask import Flask, render_template app = Flask(__name__) # Also specify the template directory # app = Flask(__name__, template_folder="/opt/python-projects/flask") @('/') def hello(): name = "Alice" return render_template('', name=name) if __name__ == '__main__': (host='0.0.0.0', port=8000, debug=True)
In the code above, the variablename
pass on to Template.
<!-- templates/(architecture) formwork --> <!DOCTYPE html> <html> <head> <title>variable</title> </head> <body> <h1>hello {{ name }}!</h1> </body> </html>
fulfillment
python3
interviews
curl http://192.168.182.110:8000/
2) Control structure
In Jinja2, you can use theif
、for
cap (a poem)while
and other statements to control the output in the template. The sample code is as follows:
# # Using if control structures in Flask from flask import Flask, render_template app = Flask(__name__) @('/') def hello(): user = {"name": "Alice", "age": 25} return render_template('', user=user) if __name__ == '__main__': (host='0.0.0.0', port=8000, debug=True)
templates/
Template files
<!-- (architecture) formwork --> <!DOCTYPE html> <html> <head> <title>Hello</title> </head> <body> {% if user %} {% if >= 18 %} <h1>Hello {{ }}, you are an adult!</h1> {% else %} <h1>Hello {{ }}, you are a minor!</h1> {% endif %} {% else %} <h1>Hello, anonymous user!</h1> {% endif %} </body> </html>
In the above code, an if statement is used to control the output to display different messages depending on the age of the user.
3) Cyclic structure
In Jinja2, you can use thefor
statement to loop through the content of the output template. The sample code is as follows:
# # Using for loop structure in Flask from flask import Flask, render_template app = Flask(__name__) @('/') def hello(): users = [{"name": "Alice", "age": 25}, {"name": "Bob", "age": 30}] return render_template('', users=users) if __name__ == '__main__': (host='0.0.0.0', port=8000, debug=True)
templates/
Template files
<!-- (architecture) formwork --> <!DOCTYPE html> <html> <head> <title>Hello</title> </head> <body> {% for user in users %} <h1>Hello {{ }}!</h1> <p>You are {{ }} years old.</p> {% endfor %} </body> </html>
In the code above, using thefor
loop to iterate through the list of users and output information about each user.
4) Macros
In Jinja2, you can use macros to define a piece of code that can be reused block, sample code is as follows:
# # Using Macros in Flask from flask import Flask, render_template app = Flask(__name__) @('/') def hello(): users = [{"name": "Alice", "age": 25}, {"name": "Bob", "age": 30}] return render_template('', users=users) if __name__ == '__main__': (host='0.0.0.0', port=8000, debug=True)
Define a macrotemplates/
(architecture) formwork
# Define a macro {% macro print_user(user) %} <h1>Hello {{ }}!</h1> <p>You are {{ }} years old.</p> {% endmacro %}
In the code above, a code namedprint_user
macros, which can be used in templates via theimport
Import macros and use them to export user information. Templatestemplates/
<!-- (architecture) formwork --> <!DOCTYPE html> <html> <head> <title>Hello</title> </head> <body> {% for user in users %} {% import '' as macros %} {{ macros.print_user(user) }} {% endfor %} </body> </html>
In the above code, a macro named print_user is defined to output user information.
5) Filter
In Jinja2, filters can handle variables, such as formatting dates, case conversion and so on. The sample code is as follows:
# # Using Filters in Flask from flask import Flask, render_template import datetime app = Flask(__name__) @('/') def hello(): now = () return render_template('', now=now) # Custom filters @app.template_filter('datetimeformat') def datetimeformat(value, format='%Y-%m-%d %H:%M:%S'): return (format) if __name__ == '__main__': (host='0.0.0.0', port=8000, debug=True)
Template filestemplates/
<!-- (architecture) formwork --> <!DOCTYPE html> <html> <head> <title>Hello</title> </head> <body> <p>The current date and time is: {{ now|datetimeformat }}</p> </body> </html>
In the code above, a code nameddatetimeformat
filters for formatting dates and times. Here are the custom filters, in fact JinJa2 also has some built-in filters. built-in filters in Jinja2:/en/3./te…
Filter Name | account for | give an example |
---|---|---|
abs(value) | Returns the absolute value of a value | {{ -1|abs }} |
int(value) | Converting values to int types | {{ param | int }} |
float(value) | Converting values to float types | |
string(value) | Converting variables to strings | |
default(value,default_value,boolean=false) | If the current variable has no value, the value in the argument is used instead. If you want to use python's form of determining if it is false, you can pass boolean=true. you can also use or instead of | {{ name|default('xiaotuo') }} |
safe(value) | If global escaping is turned on, then the safe filter turns off escaping for the variable | {{ content_html|safe }} |
escape(value) or e | Escape characters, will escape symbols such as <, > etc. into HTML symbols | {{ content|escape or content|e }} |
first(value) | Returns the first element of a sequence | {{ names|first }} |
format(value,*arags,**kwargs) | Formatting strings | %s"-"%s"|format('Hello?', "Foo!") }} Output Hello?-Fool! |
last(value) | Returns the last element of a sequence. | {{ names|last }} |
length(value) | Returns the length of a sequence or dictionary. | {{ names|length }} |
join(value,d='+') | Splice a sequence into a string with the value of the parameter d | |
lower(value) | Convert strings to lowercase | |
upper(value) | Convert strings to lowercase | |
replace(value,old,new) | Replace the string that replaces old with new. | |
truncate(value,length=255,killwords=False) | Intercepts strings of length | |
striptags(value) | Removes all HTML tags from the string and replaces them with a single space if multiple spaces occur | |
trim | Intercepts whitespace characters before and after a string. | {{ str123 | trim }} |
wordcount(s) | Counting the number of words in a long string |
6) Inheritance
In Jinja2, you can use inheritance to create a template that contains common elements and create more specific templates by inheriting that template. The sample code is as follows:
# # Using Inheritance in Flask from flask import Flask, render_template app = Flask(__name__) @('/') def hello(): return render_template('') if __name__ == '__main__': (host='0.0.0.0', port=8000, debug=True)
Template filestemplates/
<!-- (architecture) formwork --> <!DOCTYPE html> <html> <head> <title>{% block title %}{% endblock %}</title> </head> <body> {% block content %}{% endblock %} </body> </html>
Template filestemplates/
<!-- (architecture) formwork --> {% extends "" %} {% block title %}Hello{% endblock %} {% block content %} <h1>Hello World!</h1> {% endblock %}
In the code above, a code named The template for the
The template is inherited in the template.
Templates can be overridden in the
block in the template and add new content to it.
7) Contains
In Jinja2, you can use include to include a template into another template. The sample code is as follows:
# # Use Flask to include the from flask import Flask, render_template app = Flask(__name__) @('/') def hello(): return render_template('') if __name__ == '__main__': (host='0.0.0.0', port=8000, debug=True)
Template filestemplates/
<!-- (architecture) formwork --> <!DOCTYPE html> <html> <head> <title>{% block title %}{% endblock %}</title> </head> <body> {% block content %}{% endblock %} {% include "" %} </body> </html>
Template filestemplates/
<!-- (architecture) formwork --> <footer> <p>© 2023</p> </footer>
In the code above, a code named The template for the
The template uses an include to set the
The template is included to the bottom of the page. This avoids adding the same footer over and over again on each page.
This article describes the basics of Python Flask Jinja2 syntax, including variables, control structures, looping structures, and macros, as well as advanced features such as filters, inheritance, and includes. Using these features, it is easier to develop dynamic web applications. Use these basics to quickly develop dynamic web applications.
The above is Python Flask JinJa2 Syntax Usage Examples detailed content, more information about Python Flask JinJa2 Syntax please pay attention to my other related articles!