十七:jinja2之宏

宏有点类似于函数,接收一些数据,进行处理,但是没有返回值,可以将一些常用的代码片段放到宏中,然后把不固定的值抽出来做变量

使用maacro来定义宏,使用宏的时候,参数可以设默认值

自定义一个input标签

{% macro input(name='', value='', type='text') %}
<input type="{{ type }}", name="{{ name }}", value="{{ value }}">
{% endmacro %}

<h1>login</h1>
<table>
<tbody>
<tr>
<td>用户名:</td>
<td>{{ input('username') }}</td>
</tr>
<tr>
<td>密码:</td>
<td>{{ input('password', type='password') }}</td>
</tr>
<tr>
<td></td>
<td>{{ input(type='submit', value='提交') }}</td>
</tr>
</tbody>
</table>

真实工作情况下是把宏单独封装起来,要用的时候导入使用(起点路径为templates),导入的方式与python一样:import aaa、import aaa as bbb、from aaa import bbb as ccc

如果要在带入宏的时候,就把当前模板的一些参数传给宏所在的模板,就要在导入的时候使用with context

原文地址:https://www.cnblogs.com/zhongyehai/p/11784418.html