Question

What I'd like to achieve is to make a calculation in Django template, In plain maths that would be :

section_angle = base_angle + ( sections_length / current_iteration_counter_over_sections)

When trying to translate it in Django template, I think that could be something like :

{% for section in sections %}
    {% with base_angle|add:sections|length|divides:forloop.counter0 as section_angle %}

With a custom divides filter looking like

def divides(value, param):
    return float(param)/float(value)

I'm a bit confused about how to arrange it, the orders of filters and arguments I should use. With the example showed here, it leads to an error : Caught ValueError while rendering: could not convert string to float:

Bonus question : I tried to add parenthesis to clarify but the template engine seems to not like it.

Was it helpful?

Solution

Don't do that. The Django template system is not the place to put such a logic. Read the Philosophy comments about templates in the Django official website:

If you have a background in programming, or if you’re used to languages which mix programming code directly into HTML, you’ll want to bear in mind that the Django template system is not simply Python embedded into HTML. This is by design: the template system is meant to express presentation, not program logic.

I think the Timmy's comment is right, put the entire logic in a custom filter.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top