Skip to main content
 首页 » 编程设计

Python Jinja2 宏空白问题

2025年04月02日10JeffreyZhao

这是对我的另一个问题 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 个空格”之前多一个行

谢谢你

请您参考如下方法:

完成答案编辑。我明白你现在想要做什么,并且我有一个可行的解决方案(我在你的模板中添加了一个 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 应该可以避免这种情况,但我一定理解错了。

希望这能满足您的需求。