Reputation: 71
This is kind of extension to my other question Python Jinja2 call to macro results in (undesirable) newline.
My python program is
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)
Actual output:
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
Expected output:
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
What is undesirable (per car) is an extra newline at the beginning and an extra line before the line '2 spaces before me'
Thanks Rags
Upvotes: 3
Views: 1827
Reputation: 6616
Complete edit of answer. I see what you're going for now, and I have a working solution (I added in one if
statement to your template). Here is what I used, with all other lines of your code unchanged:
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
'''
The spacing is exactly how I'm running it on my end, giving exactly the desired output you put in your question. I confess that I am myself confused by one point, which is that I had to move the first line, {% macro print_car_review(car) %}
, up onto the same line as template_str = '''
. Based on my understanding of the docs, setting trim_blocks=True
should make that unnecessary, but I must be understanding it wrong.
Hopefully that gets you what you needed.
Upvotes: 1