19Jinja2中宏定义

 1 @app.route('/')
 2 def hello_world():
 3     return render_template('index.html')
 4 
 5 
 6 {% macro input(name="",value="",type="text") %}  7     <input type="{{ type }}" name="{{ name }}" value="{{ value }}">
 8 {% endmacro %}  9 
10 <h1>Jinja2宏</h1>
11 <table>
12     <tbody>
13     <tr>
14         <td>用户名:</td>
15         <td>{{ input('username') }}</td>
16     </tr>
17     <tr>
18         <td>密码:</td>
19         <td>{{ input('username',type="password") }}</td>
20     </tr>
21     <tr>
22         <td></td>
23         <td>{{ input('username',type="submit",value="提交") }}</td>
24     </tr>
25     </tbody>
26 </table>

 以上是基本的宏定义方法。html

一,导入宏app

若是把宏写到其余的html代码中,那么只须要这样引入。spa

在html中第一行输入:ssr

1, {% from 'macro.html' import input %}3d

2, {% from 'macro.html' import input as 别名 %}code

使用别名后记得把input也改成别名。htm

3, {% import 'macro.html' as 别名 %}blog

这里是导入了macro.html这个文件且去了别名,使用的时候为:input

别名.inputit

 

二,include

做用:每一个网页中共同的部分,只写一次,而后引用它。

语法:{% include header.html%}

示例:

{% include header.html%}

  content

{% include footer.html%}

 

三,set和with

使用set语句定义变量。

 语法:{% set user =''知了''  %},一旦定义了这个变量,那么在后面的代码中均可以使用这个变量。

示例:

{% set user =''知了''  %}

用户名:{{ user }}

with的用法:只能做用在代码块中,他是带endwidth的。

{% with user =''知了''  %}

用户名:{{ user }}

{% endwith %}

还有一种with和set结合的用法:

{%  with %}

  {% set classroom = "知了" %}

  <p> {{ classroom }} </p>

{%  endwidth  %}

这样就可以作到把set限定在代码块而非整个文件中。

相关文章
相关标签/搜索