【问题标题】:Python Jinja2 macro whitespace issuesPython Jinja2 宏空白问题
【发布时间】: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


【解决方案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 应该是不必要的,但我一定是理解错了。

希望这能满足您的需求。

【讨论】:

  • 查看我编辑的问题,如果还有什么不清楚的地方请告诉我。
  • 编辑了我的答案以匹配您编辑的问题。
  • 这可行,但这是一种解决方法。我创建宏的全部目的是避免调用者必须这样做。在我的情况下,我必须调用这个宏 10 次,每个调用者现在都是 2 行。实际上,我的宏中的条件比这个例子更复杂。这看起来不像 JINJA 中的错误吗?鉴于 trim_blocks=true 加上不应出现空的新行,因此不应要求使用减号..
  • 我明白了。你可能是对的。您可以尝试通过jinja github 提交。抱歉,我无法为您提供更好的解决方案。
  • 感谢 github,我正在努力寻找提交问题的地方。归档github.com/pallets/jinja/issues/612
猜你喜欢
  • 1970-01-01
  • 2021-06-06
  • 2018-01-06
  • 2010-11-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-02
  • 2011-07-20
相关资源
最近更新 更多