Cult of Logic-Less Templates
Separation of Concerns My Ass
Undoubtedly, business and presentational logic should be kept separate. The claim that logic-less templates keep business logic out of templates is true, but why does no one consider the other side of the story: keeping presentational logic out of business code? With lobotomized template systems like Mustache, you are forced to perform a bunch of "data-massaging" in your code before running it through the template system. Not only does it feel like stepping back into the iron age, this actually violates SoC!
The reality is: dividing business and presentational logic is a design problem that requires you to use your brain. Yes, you! You can’t make the problem go away by redefining presentational logic as a simple JSON-to-string transformation. In fact, presentational logic doesn’t give a damn about your lazy opinions, it just is. Your job is to find it and consolidate it.
Less is More
The less features you are given, the more code you will have to write on your own. Micro- this and minimalist that come at a price: you will inevitably find yourself reinventing the wheel. If your templating system doesn’t support conditionals, or sorting or date formatting, you will have to implement it all yourself, in the god-awful data-massaging portion of your code. Data-massaging makes me want to pour salt on snails.
So, what’s the solution?
I think Django has a very good approach:
- Your Controllers (or Views, whatever) pass the relevant Models into the template system
- The template system handles all presentational logic, traversing model relationships by calling on the model system when necessary. This can be and often is part of presentational logic (e.g. showing the latest activity on a user’s profile page). Of course, all operations should be read-only.
- When multiple templates need the same data processing for a particular model, factor that processing into the model, and call this method from the template system (e.g. full name = first name + last name).
- When multiple templates need the same data processing for different models, extend the template system.
This calls for a real templating system, not a gimmick. It should:
- Handle all kinds of presentational logic (even if statements gasp)
- Encourage Separation of Concerns
- Be extensible, have a rich library of generic, useful functions such as date formatting, truncation, pluralization etc.
- Support template inheritance (if used for website layouts).
Be wary of technological solutions to design problems, more often than not they are a scam!