Login

Snippets by waterson

Snippet List

Functional Filters

I've been working on a project where I realized that I wanted to call methods on Python objects *with arguments* from within a Django template. As a silly example, let's say your application maintains users and "permissions" that have been granted to them. Say that permissions are open-ended, and new ones are getting defined on a regular basis. Your `User` class has a `check_permission(p)` method that return `True` if the user has been granted the permission `p`. You want to present all the users in a table, with one row per user. You want to each permission to be presented as a column in the table. A checkmark will appear in cells where a user has been granted a particular permission. Normally, in order to achieve this, you'd need to cons up some sort of list-of-dicts structure in Python and pass that as a context argument. Ugh! Here's how you'd use the `method`, `with`, and `call` filters to invoke the `check_permission` method from within your template. (Assume that you've provided `users` and `permissions` as context variables, with a list of user and permission objects, respectively.) <table> <tr> <th></th> {% for p in permissions %} <th>{{ p.name }}</th> {% endfor %} </tr> {% for u in users %} <tr> <td>{{ u.name }}</td> {% for p in permissions %} <td> {% if user|method:"check_permission"|with:p|call" %}X{% endif %} </td> {% endfor %} </tr> {% endfor %} </table> The `call_with` method is a shortcut for single-argument invocation; for example, we could have re-written the above as {% if user|method:"check_permission"|call_with:p %}...{% endif %} Anyway, this has been useful for me. Hope it's helpful for others! --chris P.S., tip o' the cap to Terry Weissman for helping me polish the rough edges!

  • filter
  • filters
  • function
  • object
  • method
Read More

waterson has posted 1 snippet.