Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'm using Django 1.3. If I put the following fragment into my template:

{% if 'my string'|length > 10 %}{{ 'my string'|length }}{% endif %}

the rendering engine prints '9'. The only thing I can think of is that the |length filter is returning a string, but that seems odd in the extreme. Can anyone point me in the right direction?

Thanks!

Edit:

The length I actually want to test comes from flatpage.title provided by django.contrib.flatpages. For this reason, I'd rather not hack the view to provide the information I need to the template. I'd hoped I could simply use the |length filter as described in the Django docs, here. However, as has been pointed out, the only way to do this seems to be to also use the |get_digit filter, whose behaviour is not clearly defined in this respect. :(

like image 365
simon Avatar asked May 02 '11 08:05

simon


People also ask

What does {% %} mean in Django?

{% %} and {{ }} are part of Django templating language. They are used to pass the variables from views to template. {% %} is basically used when you have an expression and are called tags while {{ }} is used to simply access the variable.

What does {% include %} do?

{% include %} Processes a partial template. Any variables in the parent template will be available in the partial template. Variables set from the partial template using the set or assign tags will be available in the parent template.

What is {% block content %} in Django?

{% block %}{% endblock %}: This is used to define sections in your templates, so that if another template extends this one, it'll be able to replace whatever html code has been written inside of it. Blocks are identified by their name. Usage: {% block content %} <html_code> {% endblock %} .

Do Django templates have multiple extends?

Yes you can extend different or same templates.


2 Answers

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.

like image 125
dting Avatar answered Sep 17 '22 23:09

dting


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

like image 42
Silver Light Avatar answered Sep 18 '22 23:09

Silver Light