djangodjango-templates

How to use method parameters in a Django template?


I know there is a post here: django template system, calling a function inside a model describing how you can make a custom template filter to achieve this, but from a programmer's standpoint this is a failure because that's hacking something that isn't meant for that. It seems almost ridiculous that you can't call a method with parameters in Django's template system.


Solution

  • The Django team has decided, as a matter of philosophy, not to allow passing method parameters in a view. Personally, I agree with them; it forces a separation of logic and presentation that I find helpful. It prevents the kind of spaghetti code that PHP is notorious for.

    The right thing to do in the case you linked is to pass the result of that call from the view into the template via the context. It's just more maintainable that way. If later you need to change my_related_deltas(3) to my_related_deltas(4), you go to the view, which should be fairly concise, instead of searching through templates to figure out exactly where it is defined.