宏
模板中的宏跟python中的函数类似,可以传递参数,但是不能有返回值,可以将一些经常用到的代码片段放到宏中,然后把一些不固定的值抽取出来当成一个变量
import语句
在真实的开发中,会将一些常用的宏单独放在一个文件中,在需要使用的时候,再从这个文件中进行导入。import语句的用法跟python中的import类似,可以直接import…as…,也可以from…import…或者from…import…as…,假设现在有一个文件,叫做forms.html,里面有两个宏分别为input和textarea
另外需要注意的是,导入模板并不会把当前上下文中的变量添加到被导入的模板中,如果你想要导入一个需要访问当前上下文变量的宏,有两种可能的方法
• 显式地传入请求或请求对象的属性作为宏的参数
• 与上下文一起(with context)导入宏
与上下文中一起(with context)导入的方式
@app.route("/macro/")
def macro():
return render_template("macro.html")
通过自定义-“宏”-input标签只写了一次-通过传参的方式来完成需求 - 快速创建input标签
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
{% macro input(name,value='', type='text') %}
<input type="{{ type }}", name="{{ name }}", value="{{ value }}">
{% endmacro %}
<table>
<tr>
<td>用户名:</td>
<td>{{ input('username') }}</td>
</tr>
<tr>
<td>密码:</td>
<td>{{ input('password',type='password') }}</td>
</tr>
<tr>
<td>密码:</td>
<td>{{ input(value='提交',type='submit')}}</td>
</tr>
</table>
</body>
</html>
import …as
导入宏:
两种导入方式:
with context - 给模版传参