Question

I've written a templatetag that includes much of the logic that I would normally expect to find in a view. While writing some unit tests I started wondering about a slightly different approach. I don't feel experienced enough to judge the pros and cons (maybe this is even a well known practice – or a no go...). That's why I am interested in your opinion.

My idea was to write a view to handle all the logic and to use the templatetag as a wrapper that passes all relevant context to that view and returns the rendered HTML.

Advantages that I would hope to get from this approach:

  • easier to provide different output formats
  • easier DRY
  • easier testing
  • permission checks using decorators and mixins inside the view
  • cache control inside the view
  • nice approach towards ajax and/or edge side includes
  • higher flexibility

For example, a templatetag that renders a tree navigation could deliver HTML when accessed through the templatetag while at the same time its corresponding view remains accessible through a URL.

The view could provide different output formats like JSON, RSS, XML, handle permission checking, ... Advanced logic could be tested through the view, leaving responsibility for the templatetag testcases just to ensure the very basics.

I'd appreciate other opinions, hints or links to packages or related posts.

Was it helpful?

Solution

In my opinion, the problem with template tags are:

  1. Too much abstraction.
  2. Challenging to test.
  3. Problems with performance

What I suggest instead is:

  1. Create a function that generates the data, caches the data, handles permissions, anything else data related
  2. Write three more functions that render the data in HTML, JSON, and XML respectively
  3. Document and write tests for the above functions
  4. Use these functions in views, filters, and template tags as needed. The views/filters/tags calling the functions would be very thin and easy to manage.

The benefits you get by this approach are:

  1. Reusable code
  2. More easily testable code
  3. Better speed
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top