Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I compare a template variable to an integer in Django/App Engine templates?

Using Django templates in Google App Engine (on Python), is it possible to compare a template variable to an integer in an {% if %} block?

views.py:

class MyHandler(webapp.RequestHandler):
    def get(self):
        foo_list = db.GqlQuery(...)
        ...
        template_values['foos'] = foo_list
        template_values['foo_count'] = len(foo_list)
        handler.response.out.write(template.render(...))

My template:

{% if foo_count == 1 %}
     There is one foo.
{% endif %}

This blows up with 'if' statement improperly formatted.

What I was attempting to do in my template was build a simple if/elif/else tree to be grammatically correct to be able to state

#foo_count == 0:
There are no foos.

#foo_count == 1:
There is one foo.

#else:
There are {{ foos|length }} foos.

Browsing the Django template documents (this link provided in the GAE documentation appears to be for versions of Django far newer than what is supported on GAE), it appears as if I can only actually use boolean operators (if in fact boolean operators are supported in this older version of Django) with strings or other template variables.

Is it not possible to compare variables to integers or non-strings with Django templates?

I'm sure there is an easy way to workaround this - built up the message string on the Python side rather than within the template - but this seems like such a simple operation you ought to be able to handle in a template.

It sounds like I should be switching to a more advanced templating engine, but as I am new to Django (templates or any part of it), I'd just like some confirmation first.

like image 525
matt b Avatar asked May 05 '10 01:05

matt b


People also ask

Which characters are illegal in template variable name in Django?

Variable names consist of any combination of alphanumeric characters and the underscore ( "_" ) but may not start with an underscore, and may not be a number.

What is a more efficient way to pass variables from template to view in Django?

POST form (your current approach)

How do I use a variable in a template?

In the template, you use the hash symbol, # , to declare a template variable. The following template variable, #phone , declares a phone variable with the <input> element as its value. Refer to a template variable anywhere in the component's template.


1 Answers

right:

{% if foo_list == 1 %}

wrong:

{% if foo_list== 1 %}
like image 77
xxxxx Avatar answered Sep 28 '22 11:09

xxxxx