Your (HTML) template language should have conditionals

December 19, 2013

You could call this a war story, or just learning from my painful experience.

Back when I was first writing DWiki and didn't have enough experience to know better, I decided that it should have a quite simply template language because it would be easy to implement and it would avoid the temptation to do lots of things in templates. As part of this simplicity I decided that there would be no 'if' conditional operator.

(There is a slightly subtle reason for avoiding this. If you have no 'if' and no looping, you can do template expansion one operator at a time with text substitution because you need no lookahead; you just find the next operator, expand it on the spot, and insert the expansion. If you add 'if' or loops, you now have a pattern of '<if ...> text <else> other text <endif>' and you need some parsing.)

Of course I wound up needing conditional stuff anyways, so I invented conditional template inclusion and some other tricks. This preserved the simplicity of my template expansion code but had another drawback. Instead of having templates with conditional logic, I instead wound up with an explosion of templates; every separate 'if' clause basically had to become a separate (conditionally included) template.

(You don't want to know how the actual conditions are implemented. I swear, it made sense at the time.)

An explosion of templates is not a usability improvement over conditional logic in templates. Rather the contrary, because it's much harder to see and follow things across five or six separate files than it would be if everything was in one place. In the end almost any templating system is going to have some form of conditionality; the only question is where it emerges and how ugly the result is. I've come around to the view that having actual 'if' conditional operators is the least bad way even if they do complicate various things and risk your templates becoming increasingly hard to follow.

(And I know, real templating systems have dealt with all of these issues long ago and for any real project you should almost certainly not try to write your own templating system but adopt an existing one, which renders all of this moot. DWiki was a special case for all sorts of reasons.)

Written on 19 December 2013.
« Thinking about what we'll need for reproducible OmniOS installs
A realization: on the modern web, everything gets visited »

Page tools: View Source, Add Comment.
Login: Password:
Atom Syndication: Recent Comments.

Last modified: Thu Dec 19 02:46:14 2013
This dinky wiki is brought to you by the Insane Hackers Guild, Python sub-branch.