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. :(
{% %} 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.
{% 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.
{% 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 %} .
Yes you can extend different or same templates.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With