djangodjango-templates

Variable subtraction in django templates


It is able to write {{ myval.add:5 }}, {{ myval|add:value }} and even {{ myval|add:-5 }}.

However, I can't find out what I should type to add value * -1 like {{ myval|add:-value }}. This doesn't work, sadly.


Solution

  • The built-in Django template tags/filters aren't all-encompassing, but it's super easy to write your own custom template tags: https://docs.djangoproject.com/en/dev/howto/custom-template-tags/

    You could make your own subtract template tag pretty easily:

    @register.filter
    def subtract(value, arg):
        return value - arg