Flask模板的介绍与使用 | 您所在的位置:网站首页 › jinja2 模板引擎 › Flask模板的介绍与使用 |
Flask模板的简单介绍
在Flask web程序中,通过业务逻辑函数得到的数据后,接下来需要根据这些数据生成HTTP响应(对于Web应用来说,HTTP响应是一个HTML文件)。在Flask Web开发中,一般是提供一个HTML模板文件,然后将数据传递到模板中,在渲染HTML模板文件后会得到最终的HTML响应文件。 使用Jinja2模板引擎在Flask框架中,是使用Jinja2模板引擎对模板文件进行渲染,如果想要开发出一套易于维护的程序,那么就一定要将它的业务代码与逻辑代码分开。在Flask框架中,视图函数的作用是生成对访问请求的响应,一般来说,访问请求会改变程序的状态,而这种变化也会在视图函数中产生。在Flask程序中,业务逻辑部分也就是我们的后台,一般就是在python文件中编写,表现逻辑部分就会在HTML文件中编写,也就是模板文件。 在Flask程序中,模板文件是存储在templates文件夹中的,现在在templates文件夹中创建两个模板文件index.html与user.html,它们的代码,如下所示: index.html Hello worlduser.html hello {{name}}在默认的情况下,Flask在程序文件夹中,会自动寻找templates子文件夹中的模板文件。 接下来,新建一个moban.py文件,代码如下所示: from flask import Flask, render_template app = Flask(__name__) @app.route('/') def index(): return render_template('index.html') @app.route('/user/') def user(name): return render_template('user.html', name=name) if __name__ == '__main__': app.run()在上述代码中使用Flask的内置函数render_template()引用Jinja2模板引擎。 render_template函数的用法: (function) render_template: (template_name_or_list: str | List[str], **context: Any) -> str Renders a template from the template folder with the given context. :param template_name_or_list: the name of the template to be rendered, or an iterable with template names the first one existing will be rendered :param context: the variables that should be available in the context of the template.第一个参数:表示本程序使用的模板文件名。 第二个参数:是一个“键-值”对,表示模板中变量对应的真实值。 Jinja2模板的基本元素前面的Jinja2模板文件的index.html和user.html中,页面元素比较简单,在Jinja2模板文件中可以有更多的元素。 变量在模板文件中user.html,“{{nme}}代码部分表示一个变量,功能是告诉模板引擎这个位置的信息是由业务逻辑进行处理。Jinja2非常强大,它除了可以识别普通变量之外,还可以识别其他类型的变量,例如列表、字典和对象等。 字典中的值:{{mydict['key']}} 列表中的值:{{mydict[3]}} 列表中的值,具有可变索引:{{mydict[myintvar]}} 对象方法中的值:{{myjob.somemethod()}} 过滤器开发者如果想要修改变量的值,可以将过滤器添加到变量名的后面,在中间使用竖线进行隔离,例如,在模板文件中想要以首字母大写的形式显示变量name的值。 {{name | capitalize}} Jinja2中常见的过滤器(1)capitalize:把变量值的首字母转换成大写,将其他字母转换为小写。 (2)lower:把变量值全部转换为小写 (3)upper:把所有变量值转换为大写 (4)title:把变量中的所有单词的首字母都转换为大写 (5)trim:删除变量值中的首位空格 (6)stripags:在渲染前删除变量值中的所有HTML标签 下面代码将演示Flask Web中模板传递变量的方式。 untitled.py from flask import Flask, render_template class Myobj(object): def __init__(self, name) -> None: self.name = name def get_name(self): return self.name app = Flask(__name__) @app.route('/') def index(): mydict = {'key1': '123', 'key2': 'hello'} mylist = [123, 234, 456] myintvar = 0 myobj = Myobj('Hyman') return render_template('index.html', mydict=mydict, mylist=mylist, myintvar=myintvar, myobj=myobj) if __name__ == '__main__': app.run()index.html Document一个来自字典的值:{{mydict['key']}} 一个来自列表的值:{{mylist[3]}} 一个来自具有变量索引的列表值{{mylist[myintvar]}} 一个来自对象方法的值{{myobj.get_name()}} 控制结构Flask中的Jinja2模板提供了多种控制结构,通过这些控制结构可以改变模板的渲染过程。例如,下面展示的条件控制语句。 { %if user %} 你好{{user}},欢迎登录 {% else %} 登录错误 { %endif% }接下来在下面掩饰for循环在模板中的使用。 {% for user in users %} 用户列表:{{user}} {{% endfor %}}下面编写两个文件来实现控制结构与循环结构的使用。 app.py from turtle import title from flask import Flask, render_template app = Flask(__name__) @app.route('/') def index(): list1 = list(range(10)) my_list = [ {'id': 1, 'value': '我爱工作'}, {'id': 2, 'value': '工作使人快乐'}, {'id': 3, 'value': '沉迷工作无法自拔'}, {'id': 4, 'value': '日渐消瘦'}, {'id': 5, 'value': '以梦为马,不负韶华'},] return render_template('index.html', title='hello world',list2=list1,my_list=my_list) def do_listreverse(aa): temp_li = list(aa) temp_li.reverse() return temp_li app.add_template_filter(do_listreverse, 'listreverse') if __name__ == '__main__': app.run()index.html Document {{title | listreverse | upper}} {% for item in my_list %} {{item.id}}----{{item.value}} {% endfor %} {% for item in my_list %} {% if loop.index == 1 %} {{loop.index}}----{{item.get('value')}} {% elif loop.index == 2 %} {{loop.index}}----{{item.get('value')}} {% elif loop.index == 3 %} {{loop.index}}----{{item.get('value')}} {% else %} {{loop.index}}----{{item.get('value')}} {% endif %} {% endfor %} 静态文件在flask web程序中也同样可以使用静态文件,假如你是使用Pycharm创建Flask项目,它会自动生成static文件夹,该文件夹就是用于存储静态文件,比如说图片、css文件和JavaScript文件等。 app.py from flask import Flask, render_template app = Flask(__name__) @app.route('/') def index(): return render_template('index.html') if __name__ == '__main__': app.run()index.html Documenthello.js function sayhello(){ alert ("你好"); }在上面的代码中,hello.js是保存在静态文件夹static中。 |
CopyRight 2018-2019 实验室设备网 版权所有 |