Flask 简明教程

Flask – Templates

可以以 HTML 形式返回绑定至某个 URL 的函数的输出。例如,在以下脚本中, hello() 函数将使用附加了 <h1> 标记的 ‘Hello World’ 呈现。

It is possible to return the output of a function bound to a certain URL in the form of HTML. For instance, in the following script, hello() function will render ‘Hello World’ with <h1> tag attached to it.

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)

但是,从 Python 代码中生成 HTML 内容很麻烦,尤其当需要放置变量数据和 Python 语言元素(如条件语句或循环)时。这需要频繁地转义 HTML。

However, generating HTML content from Python code is cumbersome, especially when variable data and Python language elements like conditionals or loops need to be put. This would require frequent escaping from HTML.

这正是我们可以利用 Flask 所基于的 Jinja2 模板引擎的地方。可以使用 render_template() 函数呈现 HTML 文件,而不从函数返回硬编码的 HTML。

This is where one can take advantage of Jinja2 template engine, on which Flask is based. Instead of returning hardcode HTML from the function, a HTML file can be rendered by the render_template() function.

from flask import Flask
app = Flask(__name__)

@app.route('/')
def index():
   return render_template(‘hello.html’)

if __name__ == '__main__':
   app.run(debug = True)

Flask 会尝试在模板文件夹中查找 HTML 文件,该文件夹与该脚本存在的文件夹相同。

Flask will try to find the HTML file in the templates folder, in the same folder in which this script is present.

  1. Application folder Hello.pytemplates hello.html

术语 ‘web templating system’ 涉及设计 HTML 脚本,可在其中动态插入变量数据。Web 模板系统包含一个模板引擎、某种数据源和一个模板处理器。

The term ‘web templating system’ refers to designing an HTML script in which the variable data can be inserted dynamically. A web template system comprises of a template engine, some kind of data source and a template processor.

Flask 使用 jinja2 模板引擎。Web 模板包含穿插放置的变量和表达式(在此情况下为 Python 表达式)的 HTML 语法,这些变量和表达式在呈现模板时会被替换值。

Flask uses jinja2 template engine. A web template contains HTML syntax interspersed placeholders for variables and expressions (in these case Python expressions) which are replaced values when the template is rendered.

以下代码作为 hello.html 保存到模板文件夹中。

The following code is saved as hello.html in the templates folder.

<!doctype html>
<html>
   <body>

      <h1>Hello {{ name }}!</h1>

   </body>
</html>

接下来,从 Python shell 运行以下脚本。

Next, run the following script from Python shell.

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)

在开发服务器开始运行后,打开浏览器并输入 URL,如下所示: http://localhost:5000/hello/mvl

As the development server starts running, open the browser and enter URL as − http://localhost:5000/hello/mvl

URL 的 variable 部分插入到 {{ name }} 占位符中。

The variable part of URL is inserted at {{ name }} place holder.

web templating system example

jinja2 模板引擎使用以下定界符从 HTML 中转义。

The jinja2 template engine uses the following delimiters for escaping from HTML.

  1. {% …​ %} for Statements

  2. {{ …​ }} for Expressions to print to the template output

  3. {# …​ #} for Comments not included in the template output

  4. # …​ ## for Line Statements

在以下示例中,演示了模板中的条件语句用法。指向 hello() 函数的 URL 规则接受整数参数。它传到 hello.html 模板。在其内部,比较收到的数字值(分数)(大于或小于 50),并相应地有条件地呈现 HTML。

In the following example, use of conditional statement in the template is demonstrated. The URL rule to the hello() function accepts the integer parameter. It is passed to the hello.html template. Inside it, the value of number received (marks) is compared (greater or less than 50) and accordingly HTML is conditionally rendered.

Python 脚本如下 −

The Python 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)

hello.html 的 HTML 模板脚本如下 −

HTML template script of hello.html is as follows −

<!doctype html>
<html>
   <body>
      {% if marks>50 %}
         <h1> Your result is pass!</h1>
      {% else %}
         <h1>Your result is fail</h1>
      {% endif %}
   </body>
</html>

请注意,条件语句 if-elseendif 用分隔符 {%..%} 括起来。

Note that the conditional statements if-else and endif are enclosed in delimiter {%..%}.

运行 Python 脚本并访问 URL http://localhost/hello/60 ,然后访问 http://localhost/hello/30 ,以查看 HTML 按条件更改的输出。

Run the Python script and visit URL http://localhost/hello/60 and then http://localhost/hello/30 to see the output of HTML changing conditionally.

Python 循环构造也可以在模板内部使用。在以下脚本中,当在浏览器中打开 URL http://localhost:5000/result 时,函数 result() 将一个字典对象发送到模板 results.html

The Python loop constructs can also be employed inside the template. In the following script, the result() function sends a dictionary object to template results.html when URL http://localhost:5000/result is opened in the browser.

result.html 的模板部分使用 for loop ,以将字典对象 result{} 的键值对作为 HTML 表格的单元格来呈现。

The Template part of result.html employs a for loop to render key and value pairs of dictionary object result{} as cells of an HTML table.

从 Python Shell 中运行以下代码。

Run the following code from Python shell.

from flask import Flask, render_template
app = Flask(__name__)

@app.route('/result')
def result():
   dict = {'phy':50,'che':60,'maths':70}
   return render_template('result.html', result = dict)

if __name__ == '__main__':
   app.run(debug = True)

将以下 HTML 脚本保存为 result.html ,放在模板文件夹中。

Save the following HTML script as result.html in the templates folder.

<!doctype html>
<html>
   <body>
      <table border = 1>
         {% for key, value in result.items() %}
            <tr>
               <th> {{ key }} </th>
               <td> {{ value }} </td>
            </tr>
         {% endfor %}
      </table>
   </body>
</html>

此处,对应于 For 循环的 Python 语句同样用 {%..%} 括起来,而表达式 key and value 则放在 {{ }} 中。

Here, again the Python statements corresponding to the For loop are enclosed in {%..%} whereas, the expressions key and value are put inside {{ }}.

开发开始运行后,在浏览器中打开 http://localhost:5000/result ,以获取以下输出。

After the development starts running, open http://localhost:5000/result in the browser to get the following output.

table template example