2016-09-26 71 views
2

這是對我的另一個問題Python Jinja2 call to macro results in (undesirable) newline的擴展。Python Jinja2宏空白問題

我的Python程序

import jinja2 
template_env = jinja2.Environment(trim_blocks=True, lstrip_blocks=True, autoescape=False, undefined=jinja2.StrictUndefined) 
template_str = ''' 
{% macro print_car_review(car) %} 
    {% if car.get('review') %} 
    {{'Review: %s' % car['review']}} 
    {% endif %} 
{% endmacro %} 
hi there 
car {{car['name']}} reviews: 
{{print_car_review(car)}} 
    2 spaces before me 
End of car details 
''' 
ctx_car_with_reviews = {'car':{'name':'foo', 'desc': 'foo bar', 'review':'good'}} 
ctx_car_without_reviews = {'car':{'name':'foo', 'desc': 'foo bar'}} 
print 'Output for car with reviews:' 
print template_env.from_string(template_str).render(ctx_car_with_reviews) 
print 'Output for car without reviews:' 
print template_env.from_string(template_str).render(ctx_car_without_reviews) 

實際輸出:

Output for car with reviews: 

hi there 
car foo reviews: 
    Review: good 

    2 spaces before me 
End of car details 
Output for car without reviews: 

hi there 
car foo reviews: 

    2 spaces before me 
End of car details 

預期輸出:

Output for car with reviews: 
hi there 
car foo reviews: 
    Review: good 
    2 spaces before me 
End of car details 
Output for car without reviews: 
hi there 
car foo reviews: 
    2 spaces before me 
End of car details 

什麼是不可取的(每車)是在開始額外的換行符和在'我之前2個空格'之前的額外行

Thanks Rags

+0

要刪除空格還是要保留空格? – SumanKalyan

+0

@SumanKalyan我已經修改了我的問題,以清楚地說明預期的結果。希望現在澄清它 –

+0

@RagsRachamadugu,編輯我的答案以迴應您修改後的問題。 – coralvanda

回答

1

完整編輯答案。我明白你現在要做什麼,並且我有一個工作解決方案(我在你的模板中添加了一個if聲明)。以下是我使用,改變你的代碼的所有其他行:

template_str = '''{% macro print_car_review(car) %} 
    {% if car.get('review') %} 
    {{'Review: %s' % car['review']}} 
    {% endif %} 
{% endmacro %} 
hi there 
car {{car['name']}} reviews: 
{% if 'review' in car %} 
{{print_car_review(car)-}} 
{% endif %} 
    2 spaces before me 
End of car details 
''' 

的間距到底我快到它在我的結束,正好讓你把你的問題所需的輸出。我承認,我自己有一點困惑,那就是我必須將第一行{% macro print_car_review(car) %}上移到與template_str = '''相同的行上。根據我對文檔的理解,設置trim_blocks=True應該使其不必要,但我必須理解它是錯誤的。

希望你能得到你需要的東西。

+0

看到我編輯的問題,讓我知道如果有什麼東西還不清楚。 –

+0

編輯我的答案,以配合您編輯的問題。 – coralvanda

+0

這可行,但這是一種解決方法。我創建宏的關鍵是避免調用者必須這樣做。我必須在我的情況下調用這個宏10s,每個調用者現在是2個額外的行。實際上,我的宏觀條件比這個例子更復雜。這看起來不像JINJA中的一個bug嗎?使用減號不應該被要求給trim_blocks = true加空的新行不應該發生.. –