views:

2176

answers:

4

Im getting strangest error in django so far:

'if' statement improperly formatted

Template that raises the error is this:

{% if diff >= 0 %}
<span class="pos">+{{ diff }}
{% else %}
<span class="neg">-{{ diff }}
{% endif %}
</span>
<span>{{ a }}</span>

view that has a and diff in context is this:

def add(request, kaart_id):
    if request.is_ajax() and request.method == 'POST':
     x = Kaart.objects.get(id=kaart_id)
     x.pos += 1
     x.save
     x = Kaart.objects.get(id=kaart_id)  
     from django.utils import simplejson
     diff = x.pos - x.neg
     a = "(+1)"
     context = { 'diff':diff, 'a':a }
     return render_to_response('sum.html', context, context_instance=RequestContext(request))

It does not matter what equation i use in if, >, >=, ==.. they all raise the same error.

and as far as i can tell its all by the book: http://docs.djangoproject.com/en/dev/ref/templates/builtins/#id5

Alan.

A: 

You need to close each if statement with an endif

{% if var1 %}

{{ var1|safe }}

{% else %}

{% if var2 %}

{{ var2|safe }}

{% else %}

{% if var3 %}

{{ var3|safe }}

{% endif %}{% endif %}{% endif %}

Woot4Moo
A: 

The "smart if" tag was just added in the development version (that will eventually become 1.2).

If you're using a stable release (1.1.x or earlier) you won't be able to use those comparison operators in the "if" template tag.

Edit: look just above the == operator

John Debs
+2  A: 

Until Django 1.2 lands you are looking for "Smart If", a Django Template Tag.

A smarter {% if %} tag for django templates.

While retaining current Django functionality, it also handles

equality, greater than and less than operators. Some common case examples::

    {% if articles|length >= 5 %}...{% endif %}
    {% if "ifnotequal tag" != "beautiful" %}...{% endif %}

Arguments and operators _must_ have a space between them, so
``{% if 1>2 %}`` is not a valid smart if tag.

All supported operators are: ``or``, ``and``, ``in``, ``=`` (or

==),

``!=``, ``>``, ``>=``, ``<`` and ``<=``.
Mark Stahler
Thanks! Ill think of something else then and wait for 1.2!
Zayatzz
Just use the tag. Its really easy to load them (its in the docs) and then when 1.2 is released your code is already compatible and you can remove the tag code.
Mark Stahler
+1  A: 

As mentioned, you can't use operators in the {% if %} tag. It accepts only Boolean values (which you can AND, OR and NOT together.)

For simple equality, you can use the {% ifequal val1 val2 %} tag.

The reason is to push the "logic" out of the template and into the model layer. I.e. you should have a method on your model like so:

def positive_diff(self):
   return self.diff >= 0

Then call that in your template:

{% if x.positive_diff %} ... {% endif %}

Or, you can set an extra variable in your view:

positive_diff = diff >= 0
Tom