当前位置:网站首页>Flask (VI) - template
Flask (VI) - template
2022-06-11 09:27:00 【zju_ cbw】
Flask We can use HTML Form return is bound to a URL The output of the function .
In the following script ,hello() The function will use the additional <h1> Tag rendering 'Hello World' .
from flask import Flask
app = Flask(__name__)
@app.route('/')
def index():
return "<html><body><h1>'Hello World'</h1></body></html>"
if __name__ == '__main__':
app.run(debug=True)
however , from Python Code generation HTML The content is very troublesome , Especially when you need to place variable data and Python Language elements ( Such as condition or cycle ) when . Often need to escape HTML Code .
It can take advantage of Jinja2 Template engine technology , You don't need to return hard coded from the function HTML. As shown in the following code , Can pass render_template() Function rendering HTML file .
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def index():
return render_template('hello.html')
if __name__ == '__main__':
app.run(debug=True)
Flask Will try to find... In the same folder as the script templates In folder HTML file .
The term “Web Template system ” It means designing a HTML Script , Variable data can be inserted dynamically . Web The template system consists of a template engine , Some kind of data source and template processor .
Flask Use jinga2 template engine . Web Templates contain for variables and expressions ( These cases are Python expression ) Of HTML Syntax scatter placeholder , These variables and expressions are replaced with values when the template is rendered .
The following code is in the template (templates) Save in folder as : hello.html.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Flask HTTP Request method processing </title>
</head>
<body>
<h1>Hello {
{ name }}!</h1>
</body>
</html>
Next , Save the following code in app.py In file , And run .
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/hello/<user>')
def hello_name(user):
return render_template('hello.html', name=user)
if __name__ == '__main__':
app.run(debug=True)
When the development server starts running , Open the browser and type URL by http://localhost:5000/hello/maxsu. You can find URL The variable part of is inserted { {name}} Placeholder .
Jinja2 The template engine uses the following delimiters to start from HTML escape .
{% ... %}For multiline statements{ { ... }}Used to print out expressions to templates{# ... #}For comments that are not included in the template output# ... ##For single line statements
In the following example , Demonstrates the use of conditional statements in templates . hello() Functional URL Rules accept integer arguments . It is passed to the hello.html Templates . In it , Number received ( Mark ) The value of is compared ( Greater than or less than 50), So in HTML Performed conditional render output .
Python The script is as follows
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/hello/<int:score>')
def hello_name(score):
return render_template('hello.html', marks=score)
if __name__ == '__main__':
app.run(debug=True)
Template file :hello.html Of HTML The template script is as follows
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Flask Template example </title>
</head>
<body>
{% if marks>=60 %}
<h1> Pass the exam !</h1>
{% else %}
<h1> Fail the exam !</h1>
{% endif %}
</body>
</html>
Please note that , Conditional statements if-else and endif Included in the separator {%...%} in .
function Python Script and access URL=> http://localhost:5000/hello/60 , And then visit http://localhost:5000/hello/59, To view conditionally HTML Output .
Python The loop structure can also be used inside the template . In the following script , When opened in a browser URL => http://localhost:5000/result when ,result() Function to send the dictionary object to the template file : results.html .
result.html The template part of the adopts for Loop through the dictionary object result{} The key and value pairs of are rendered as HTML Table cells .
Python The script is as follows
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/result')
def result():
dict = {
'phy': 59, 'che': 60, 'maths': 90}
return render_template('result.html', result=dict)
if __name__ == '__main__':
app.run(debug=True)
Add the following HTML Save the script as a template folder (templates) Template file in : result.html .
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Flask Template example </title>
</head>
<body>
<table border = 1>
{% for key, value in result.items() %}
<tr>
<th> {
{ key }} </th>
<td> {
{ value }} </td>
</tr>
{% endfor %}
</table>
</body>
</html>
ad locum , And For Cycle corresponds to Python The statement is contained in {%...%} in , The expression keys and values are placed in { {}} in .
After the development starts to run , Open it in a browser http://localhost:5000/result. You can see the list of output key value pairs .
边栏推荐
- Machine learning notes - the story of master kaggle Janio Martinez Bachmann
- keyboard entry.
- Day45 storage engine data type integer floating point character type date type enumeration and set type constraints table to table relationships
- 考研数学 【数列极限证明题】题型方法总结
- 工厂出产流程中的这些问题,应该怎么处理?
- Blinn Phong reflection model
- Machine learning notes - in depth Learning Skills Checklist
- 远程办公最佳实践及策略
- 报错Version mismatch between installed depthai lib and the required one by the scrip.
- Concurrent programming
猜你喜欢

Version mismatch between installed deeply lib and the required one by the script

Résumé de la méthode d'examen des mathématiques

OpenCV CEO教你用OAK(五):基于OAK-D和DepthAI的反欺骗人脸识别系统

OpenCV OAK相机对比及介绍

MSF基于SMB的信息收集

Pulsar job Plaza | Tencent, Huawei cloud, shrimp skin, Zhong'an insurance, streamnational and other hot jobs

Day39 process object and other method mutexes

【ROS】noedic-moveit安装与UR5模型导入

Blinn Phong reflection model
![[FAQ for novices on the road] about data visualization](/img/a1/d15e286c3c886a8d3a4ac3eb165748.png)
[FAQ for novices on the road] about data visualization
随机推荐
基于SIC32F911RET6设计的腕式血压计方案
What are the types of garment ERP system in the market?
Blinn Phong reflection model
报错[error] input tesnor exceeds available data range [NeuralNetwork(3)] [error] Input tensor ‘0‘ (0)
机器学习笔记 - 使用TensorFlow的Spatial Transformer网络
Console you don't know
Kubelet error getting node help
Pulsar job Plaza | Tencent, Huawei cloud, shrimp skin, Zhong'an insurance, streamnational and other hot jobs
MySQL startup error "bind on tcp/ip port: address already in use"
Type-C蓝牙音箱单口可充可OTG方案
Set up redis highly available cluster environment
Package details
affair
报错Output image is bigger(1228800B) than maximum frame size specified in properties(1048576B)
Error [detectionnetwork (1)][warning]network compiled for 6 shapes, maximum available 10, compiling for 5 S
[software] ten skills to maximize the value of ERP system
考研數學 【數列極限證明題】題型方法總結
Openstack explanation (22) -- neutron plug-in configuration
Exclusive interview with PMC member Liu Yu: female leadership in Apache pulsar community
Opencv CEO teaches you to use oak (IV): create complex pipelines