使用python jinja2 Template的時(shí)候楞慈,在控制塊(比如一個(gè) for 標(biāo)簽幔烛、一段注釋或變 量表達(dá)式)的開始或結(jié)束放置一個(gè)減號( - ),可以移除塊前或塊后的空白囊蓝。
但用的時(shí)候總是會(huì)多出或缺失回車饿悬,所以做了些測試記錄一下。
>>> from jinja2 import Template
>>> tmpstr = '''---------
... {% for item in seq %} # 回車
... {{ item }} # 回車
... {% endfor %} # 回車
... -------------
... '''
>>> llll = [12345]
>>> tmp = Template(tmpstr)
>>> conf = tmp.render(seq=llll)
>>> print conf
---------
# 產(chǎn)生三個(gè)回車
12345
-------------
>>> tmpstr = '''---------
... {% for item in seq %} # 每次循環(huán)產(chǎn)生一個(gè)回車聚霜,2
... {{ item }} # seq有兩個(gè)元素狡恬,每個(gè)元素自己產(chǎn)生一個(gè)回車,2
... {% endfor %} # 但end只會(huì)產(chǎn)生一個(gè)回車蝎宇,1
... -------------
... '''
>>> llll = [12345, 6789]
>>> tmp = Template(tmpstr)
>>> conf = tmp.render(seq=llll)
>>> print conf
---------
12345
6789
-------------
在 for 和 endfor的后面加 "-"弟劲,可以看到回車正常了,但item前面的空格也沒了姥芥,說明for后面的"-"其消除了不止本行回車,還有下一行的空格凉唐。
>>> tmpstr = '''-------------
... {% for item in seq -%}
... {{ item }}
... {% endfor -%}
... -------------
... '''
>>> llll = [12345, 6789]
>>> tmp = Template(tmpstr)
>>> conf = tmp.render(seq=llll)
>>> print conf
-------------
12345
6789
-------------
在 endfor 前面加'-'(endfor 大括號前面有空格)庸追,可以看到 item后面的回車和endfor前面的回車都沒了。其消除了endfor之前的所有空格和回車台囱。
>>> tmpstr = '''-------------
... {% for item in seq -%}
... {{ item }}
... {%- endfor %} ## endfor 前面有空格
... -------------
... '''
>>> llll = [1234, 5678]
>>> tmp = Template(tmpstr)
>>> conf = tmp.render(seq=llll)
>>> print conf
-------------
12345678
-------------
不輸出item淡溯,可以看到endfor 前面的"-"消除了其和for之間的所有空格和回車。
>>> tmpstr = '''-------------
... {% for item in seq %} ## 前面2個(gè)空格玄坦,后面有4個(gè)空格+1個(gè)回車
... {%- endfor %} ## 前面4個(gè)空格
... -------------
... '''
>>> llll = [1234, 5678]
>>> tmp = Template(tmpstr)
>>> conf = tmp.render(seq=llll)
>>> print conf
-------------
-------------
>>>
下面這兩組測試說明,沒輪循環(huán)運(yùn)行的是 for 和endfor的后大括號和前大括號之間所有語句豺总。
第一個(gè)測試?yán)?br>
第一次循環(huán)择懂,8 * 空格(for前面) + (消除for行回車+消除item行空格的)item + 回車(item行)+2空格(endfor前面)。
第二次循環(huán)表伦,(消除for行回車+消除item行空格的)item+ 回車(item行)+2空格(endfor前面)慷丽。
總的就是。
第二個(gè)測試?yán)愃啤?/p>
>>> tmpstr = '''-------------
... {% for item in seq -%}
... {{ item }} # 前面2 * " '"
... {% endfor -%} # 前面2 * " '"
... -------------
... '''
>>> llll = [1234, 5678]
>>> tmp = Template(tmpstr)
>>> conf = tmp.render(seq=llll)
>>> print conf
-------------
1234
5678
-------------
>>> tmpstr = '''-------------
... {% for item in seq -%}
... {{ item }}
... {% endfor -%}
... -------------
... '''
>>> llll = [1234, 5678]
>>> tmp = Template(tmpstr)
>>> conf = tmp.render(seq=llll)
>>> print conf
-------------
1234
5678
-------------