Python Jinja2 macro whitespace issues
<p>This is kind of extension to my other question <a href="http://stackoverflow.com/questions/39626767/python-jinja2-call-to-macro-results-in-undesirable-newline">Python Jinja2 call to macro results in (undesirable) newline</a>. </p>

<p>My python program is</p>

<pre><code>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)
</code></pre>

<p>Actual output:</p>

<pre><code>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
</code></pre>

<p>Expected output:</p>

<pre><code>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
</code></pre>

<p>What is undesirable (per car) is an extra newline at the beginning and an extra line before the line '2 spaces before me'</p>

<p>Thanks Rags</p>

<p>Complete edit of answer.  I see what you're going for now, and I have a working solution (I added in one <code>if</code> statement to your template).  Here is what I used, with all other lines of your code unchanged:</p>

<pre><code>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
'''
</code></pre>

<p>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, <code>{% macro print_car_review(car) %}</code>, up onto the same line as <code>template_str = '''</code>.  Based on my understanding of the docs, setting <code>trim_blocks=True</code> should make that unnecessary, but I must be understanding it wrong.</p>

<p>Hopefully that gets you what you needed.</p>

python macros whitespace jinja2