這是對我的另一個問題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
要刪除空格還是要保留空格? – SumanKalyan
@SumanKalyan我已經修改了我的問題,以清楚地說明預期的結果。希望現在澄清它 –
@RagsRachamadugu,編輯我的答案以迴應您修改後的問題。 – coralvanda