[Fixed]-Django-templates: Why doesn't {% if "string"|length > 10 %} work at all?


Yes, filters always return a string.

You can achive the desired functionality by calculating string length in a view and do something like this:

{% if str_length > 10 %}
    {{ str_length }}
{% endif %}

Or create a custom filter for your needs: http://code.djangoproject.com/wiki/BasicComparisonFilters

Edited for typo


I’m recommending not using this but I have combined the get_digit and the length filters before to make this work.

{% if "12345678901234567890"|length|get_digit:"-1" > 20 %} 
    {{ "12345678901234567890"|length }} 
{% endif %}

results in nothing in the template, but:

{% if "12345678901234567890"|length|get_digit:"-1" > 19 %} 
    {{ "12345678901234567890"|length }} 
{% endif %}

results in:


being printed.



I know its late but as per django 2.1 your code will work. Please see below reference

{% if messages|length >= 100 %}
   You have lots of messages today!
{% endif %}


Try the following conditional:
{% if flatpage.title.10 %}


The best solution is to create variable like this:

{% with 'my_string'|length as string_length %}
    your code when you have available as INT variable string_length
{% endwith %}

Hope this helps everyone.



Going to play devil’s advocate here and ask why is this necessary in the first place? It’s one thing if you’re calculating on the value of a variable, but if it’s a hard-coded value, just put it in there in the right form. All you’re doing is adding processing overhead for something that’s static.

Leave a comment