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

10👍

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

14👍

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:

20

being printed.

👤dting

9👍

I know its late but as per django 2.1 your code will work. Please see below reference
https://docs.djangoproject.com/en/2.1/ref/templates/builtins/#filters

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

4👍

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

1👍

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.

👤Alex

-1👍

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