convert integer to string inside a django template Mar

Every now and then I come across a situation where I'm required to do an integer to string comparison inside a Django template. I need to unify the data types before I run the comparison or else the equality will fail. This sounds like a job for template filters.

I could write my own int_to_string filter like the following (the @stringfilter converts the argument to a string before it passes the variable into the function).

from django.template.defaultfilters import stringfilter

def int_to_string(value):
    return value

However, I would then have to load the filters into the necessary templates. Yes, I know it's not hard to do, but I'm lazy. Wouldn't it be nice if there was a pre-built filter that did the conversion for me? Well I'm in luck because the slugify filter does just that.

All I need to do is slugify the integer and compare it to the string variable. It works like a charm because when using slugify on an integer, besides the int to string conversion, it won't transform the data.

{% ifequal my_integer|slugify my_string %}
Bookmark and Share
blog comments powered by Disqus