【发布时间】:2017-02-04 08:35:32
【问题描述】:
这是对我的另一个问题Python Jinja2 call to macro results in (undesirable) newline 的一种扩展。
我的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 个空格”行之前有一个额外的行
谢谢你
【问题讨论】:
-
您要删除空格还是保留空格?
-
@SumanKalyan 我已经修改了我的问题以明确说明预期结果。希望现在澄清它
-
@RagsRachamadugu,编辑了我的答案以回复您修改后的问题。
标签: python macros whitespace jinja2