2015-10-20 13 views
3

我怎樣才能產生預期的輸出?由於換行符和破折號在忍者中無法正常工作

神社模板

{%- for field in fields -%} 

- 
    name: {{field}} 
    type: string 



{%- endfor -%} 

輸出

- 
    name: operating revenue 
    type: string- 
    name: gross operating profit 
    type: string- 

預期輸出

- 
    name: operating revenue 
    type: string 
- 
    name: gross operating profit 
    type: string 

代碼

from jinja2 import Template 

fields = ["operating revenue", "gross operating profit", "EBITDA", "operating profit after depreciation", "EBIT", "date"] 
template_file = open('./fields_template.jinja2').read() 
template = Template(template_file) 
html_rendered = template.render(fields=fields) 
print(html_rendered) 
+0

感謝你的解決方案仍然不適合我,請檢查https://gist.github.com/poc7667/717bb260ed959184cdbf – newBike

回答

5

-刪除Jinja標記的第和第一個字符之間的所有空白。您在標籤的「內部」上使用-,因此將空格刪除至-字符,並在string這兩個字之後加入這兩個字符。刪除一個或另一個。

你可以在開始和你的文字,例如結束除去額外的新行,並從起始標籤內側面取出-

{%- for field in fields %} 
- 
    name: {{field}} 
    type: string 
{%- endfor -%} 

演示:

>>> from jinja2 import Template 
>>> fields = ["operating revenue", "gross operating profit", "EBITDA", "operating profit after depreciation", "EBIT", "date"] 
>>> template_file = '''\ 
... {%- for field in fields %} 
... - 
... name: {{field}} 
... type: string 
... {%- endfor -%} 
... ''' 
>>> template = Template(template_file) 
>>> html_rendered = template.render(fields=fields) 
>>> print(html_rendered) 

- 
    name: operating revenue 
    type: string 
- 
    name: gross operating profit 
    type: string 
- 
    name: EBITDA 
    type: string 
- 
    name: operating profit after depreciation 
    type: string 
- 
    name: EBIT 
    type: string 
- 
    name: date 
    type: string 
相關問題