2016-09-26 74 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加空的新行不应该发生.. –