模板概述与变量
阅读 (189593)
分享
一、概述
-
说明
模板文件就是按照特定规则书写的一个负责展示效果的HTML文件;模板引擎就是提供特定规则的解释和替换的工具
-
Jinja2
在Flask中使用的就是该模板引擎,它是由flask核心开发组人员开发的
二、变量
-
目录结构
project/ manage.py # 项目启动控制文件 templates/ # 所有的模板文件
-
渲染模板文件
在templates下创建一个模板文件(hello.html),内容如下:
<h1>Hello Flask !</h1>
-
渲染
- render_template
- render_template_string
使用
from flask import Flask,render_template,render_template_string @app.route('/') def index(): # 渲染模板文件 # return render_template('hello.html') # 渲染模板字符串 return render_template_string('<h1>渲染字符串</h1>')
-
使用变量
-
视图传递给模板的数据
-
要遵守标识符规则
-
语法
{{ var }}
在templates下创建一个模板文件var.html,内容如下:
{# 这里是注释,渲染的变量放在两个大括号中 #} <h1>Hello {{ name }}</h1>
模板渲染
from flask import Flask,render_template,render_template_string,g @app.route('/var/') def var(): return render_template('var.html', name='lucky') # 渲染模板字符串 return render_template_string('<h1 style="color:red;">{{name}}</h1>',name='内容')
注意
- 如果使用的变量不存在,则插入的是空字符串
- 在模板中使用点语法
- 可以调用对对象方法,并且可以传递参数
- 值为bool值、None时会将值转为字符串显示
- 不能修改变量的值
-
需要
登录
才可以提问哦
: