宏和import
宏
宏和python里的函数差不多,可以传递参数,但是宏没有返回值。宏和函数一样,可以将一些经常用的代码写进宏里,然后在不同的地方进行调用
宏的基本格式
{% macro input(name, value='', type='text') %} <!-- 定义宏 -->
<input name="{{ name }}", value="{{ value }}", type="{{ type }}"> <!-- 宏的功能:返回一个标签 -->
{% endmacro %}
在同一个html文件下调用
<tr>
<td>用户名:</td>
<td>{{ input('username') }}</td> <!-- 调用宏的input -->
</tr>
<tr>
<td>密码:</td>
<td>{{ input('password', type='password') }}</td>
</tr>
在不同的文件调用宏
在不同的文件调用宏,需在另外一个文件中导入宏,下面来说宏的导入
宏的导入
import
{% import 'HTML文件/macro.html' as macro %} <!--去相对于templates的路径-->
注意: 导入的宏的路径是相对于templates的路径
调用宏:
<tr>
<td>用户名:</td>
<td>{{ macro.input('username') }}</td>
</tr>
<tr>
<td>密码:</td>
<td>{{ macro.input('password', type='password') }}</td>
</tr>
from … import …
{% from 'HTML文件/macro.html' import input %}
调用宏:
<tr>
<td>用户名:</td>
<td>{{ input('username') }}</td>
</tr>
<tr>
<td>密码:</td>
<td>{{ input('password', type='password') }}</td>
</tr>