0

I want to use django built-in template tag forloop.counter0 in a math expression. This is what I came up with:

{% for category in categories %}
        <li class="wow fadeInUp" data-wow-delay="{{ forloop.counter0 * 0.1 }}s">
                //whatever
        </li>
{% endfor %}

Which I learn is wrong cause of this error:

Could not parse the remainder: ' * 0.1' from 'forloop.counter0 * 0.1'

Is it anyway to solve this issue?

Isn't there anyway that I could use a built-in function in a math expression?

Ghasem
  • 14,455
  • 21
  • 138
  • 171
  • 3
    Yep you're right, I misunderstood the counter. You can't multiply in Django templates so you could use a custom template tag or use `widthratio` tag to do the trick https://stackoverflow.com/a/33280889/8196244 – Mauricio Cortazar Jun 24 '18 at 20:27

1 Answers1

1

One can use widthratio tag to achieve this, also you can use custom templatetag, as stated in the comment by Mauricio, but in widthratio the final value should be a number and cannot be a float, so that may be problem.

So there is a third way to achieve this by using template-filters

So for multiplication you can put this in your templatetags

from django import template
register = template.Library()

@register.filter(is_safe=False)
def multiply(value, arg):
    """Multiply the arg to the value."""
    try:
        return float(value) * float(arg)
    except (ValueError, TypeError):
        try:
            return value * arg
        except Exception:
            return ''

and use this in template like

{{ forloop.counter0|multiply:'0.1' }}

{{ '0.002'|multiply:'0.21' }}  # Output : 0.00042

Here the value and the arg need not be int, it can be a float too, also no need of loading any tag for multiplication in templates.

Bijoy
  • 1,131
  • 1
  • 12
  • 23