53

I am learning jinja2 because Google App Engine recommends it.

I found this example on Wikipedia: http://en.wikipedia.org/wiki/Jinja_%28template_engine%29

  {%- for item in item_list %}
    {{ item }}{% if not loop.last %},{% endif %}
  {%- endfor %}

What is the "-" in "{%- for"?

Also, where can I find jinja2 examples (better with Google App Engine)?

Thanks a lot!

Gaby Solis
  • 2,427
  • 5
  • 21
  • 27
  • Regarding examples, this link shows you how to set up templates https://developers.google.com/appengine/docs/python/gettingstartedpython27/templates. The documentation on jinja site will also have examples. – Rob Curtis Aug 05 '12 at 07:30
  • 1
    Similar question here: https://stackoverflow.com/questions/19401106/dashes-in-jinja-templates – theQuestionMan Oct 24 '22 at 14:53
  • Does this answer your question? [Dashes in jinja templates](https://stackoverflow.com/questions/19401106/dashes-in-jinja-templates) – Anto Oct 25 '22 at 15:55

2 Answers2

52

It suppresses extra vertical spacing, commonly used when you don't want excessive spacing between elements you're looping through.

If you put an minus sign (-) to the start or end of a block (for example a for tag), a comment or variable expression you can remove the whitespaces after or before that block

See: http://jinja.pocoo.org/docs/templates/#whitespace-control

hyperslug
  • 3,473
  • 1
  • 28
  • 29
5

As you implied the Google App Engine and Django use Jinja. Jinja uses the dash to remove or add whitespace within a block.
{%- by itself means current line should have no empty lines between current and previous line
-%} by itself means current line should have a single empty line above it
{%- and -%} means current line should be flush with previous line

In your example, you have dashes for the for loop. This will leave no space between the items. If you did not have this dash, it will leave a blank space between each item.

You can experiment here:
http://jinja.quantprogramming.com

Additional links:
Documentation
Credit

theQuestionMan
  • 1,270
  • 2
  • 18
  • 29