当前位置:网站首页>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 .

原网站

版权声明
本文为[zju_ cbw]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/03/202203012301369607.html