Flask template (1) and flask Template
The use of templates helps to separate the business logic from the presentation logic, making it easier to maintain. A template is a Web page Code that has been created. Some dynamic data must be replaced with specific values in the request context.
The Jinja2 template engine is used in flask and stored in the templates folder.
templates/index.html
Use {name} placeholder
templates/user.html
Template Rendering
Template rendering replaces the placeholder variable in the template with real values.
from flask import Flask,render_template@app.route('/')def index(): return render_template('index.html',name=name)
Variables can be obtained from lists, dictionaries, and objects.
<p>A value from a dict:{{ mydict['key'] }}</p><p>A value from a list:{{ mylist[3] }}</p><p>A value from a list with a variable index:{{ mylist[intvar] }}</p><p>A value from a object's method :{{ myobj.mymethod() }}</p>
Use the filter to modify the variable:
{{ name|capitalize }}
Common filters:
| Filter Name |
Description |
| Safe |
Do not escape during rendering |
| Capitalize |
Upper-case letters and lower-case letters |
| Lower |
Lowercase |
| Upper |
Uppercase |
| Title |
Uppercase letters of each word |
| Trim |
Remove leading and trailing Spaces |
| Striptags |
Delete all html tags in the value |
Control Structure
{% if user %} Hello,{{ user }}{% else %} Hello,Stranger!{% endif %}
<ul> {% for comment in comments %} <li>{{ comment }}</li> {% endfor %}</ul>