
2.1 使用Jinja2模板引擎

在Flask框架中,使用了一个名为Jinja2的模板引擎来渲染模板文件。在下面的内容中,将简要介绍使用Jinja2模板引擎的知识。
对于一名Web程序员来说,要想开发出易于维护的程序,必须编写形式简洁且结构良好的代码。在Flask框架中,视图函数的作用是生成对访问请求的响应。一般来说,访问请求会改变程序的状态,而这种变化也会在视图函数中产生。在Flask Web程序中,为了实现业务和逻辑的分离,将表现逻辑部分放到模板中实现,这样能够提高程序的可维护性。例如在下面的实例中,演示了在Flask Web项目中使用Jinja2模板的过程。
源码路径:daima\2\2-1\moban\
首先假设定义两个模板文件保存在templates文件夹中,这两个模板文件分别命名为index.html和user.html,其中模板文件index.html只有一行代码,具体实现代码如下所示。

模板文件user.html也只有一行代码,具体实现代码如下所示。

在默认情况下,Flask在程序文件夹中的templates子文件夹中寻找模板。接下来可以在Python程序中通过视图函数处理上面的模板文件,以便渲染这些模板。例如下面的实例文件moban.py。
源码路径:daima\2\2-1\moban\moban.py


在上述代码中,使用Flask内置函数render_template()引用Jinja2模板引擎。函数render_template('user.html',name=name)的具体说明如下所示。
• 第一个参数:表示本程序使用的模板文件名是user.html。
• 第二个参数:是一个“键-值”对,表示模板中变量对应的真实值。
上述代码中的name=name是关键字参数,其中左边的name是参数名,表示模板中使用的占位符。右边的name是当前作用域中的变量,表示同名参数的值。
在浏览器中输入“http://127.0.0.1:5000/”后,会调用模板文件index.html,执行效果如图2-1所示。在浏览器中输入“http://127.0.0.1:5000/user/Python大神”后,会调用模板文件user.html,显示用户名为“Python大神”,执行效果如图2-2所示。

图2-1 调用模板文件index.html的执行效果

图2-2 调用模板文件user.html的执行效果