上面4都是水的 恩每篇都一点知识点 用来写给不耐烦的人看。。哈哈这篇 争取不水。
上面4篇如果 掌握 基本上是 80%常用的代码了。
1、下面讲一下 比较常用的代码:
macro(jinja 上的功能)
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title></title> 6 </head> 7 <body> 8 9 {{ test }} 10 11 {# 这是注释的写法 #} 12 {# 下面是 for 的写法 #} 13 {% for n in alist %} 14 {% if n >3 %} 15 {{ n }} 16 {% endif %} 17 {% endfor %} 18 19 {% macro testm(name) %} 20 <input type="button" value="{{ name }}" name=""> 21 {% endmacro %} 22 23 {{ testm("名字1") }} 24 {{ testm("名字2") }} 25 26 </body> 27 </html>
macro 通常定义一些 重复的代码
context_processor (flask 提供的功能)
在后台 代码中添加
@app.context_processor
def process():
def test1(name):
return '<input type="button" value="{0}" name="">'.format(name)
return {'test1': test1}
前台代码 直接使用 {{ test1('名字3')|safe }} 和上面 使用 macro 是一样
上面用到 |safe 这是 jinja 提供的 filter. 这个filter 的作用是 把无转义打印 (ps:默认情况下都会将 html js 等 转义后打印 ,因为安全)
2、上面讲到 filter ,下面介绍下 其他 filter
如 int : {{ xx|int }} 将xx 转为 int 通常 使用例如: 将10.1 转为 10 或者 {% if (xx|int)==10 %}xxxxx
如 first {{ xxlist|first }} 可以 拿到list 中的 第一个元素
3、自定义 filte (2种写法)
1 @app.template_filter() 2 def add_filter(s): 3 return s + 1 4 5 6 @app.add_template_filter 7 def add_filter1(s): 8 return s + 1
使用 {{ 1|add_filter }} {{ 1|add_filter1 }}