gpt4 book ai didi

Python Jinja2 宏空白问题

转载 作者:太空宇宙 更新时间:2023-11-04 05:23:05 24 4
gpt4 key购买 nike

这是对我的另一个问题 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 应该可以避免这种情况,但我一定理解错了。

希望这能满足您的需求。

关于Python Jinja2 宏空白问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39712338/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com