There’s been a couple of posts I’ve read in the last few days discussing the merits of allowing varying amounts of code into the HTML templates in web applications. One point that some people seem to be missing with regard to code in your templates is this: I don’t care what it is, I care about what it does.
What I mean by this is that it should not be against the rules to include code in your templates providing it’s doing the right job, given its context. To take a Rails example:
<% @posts.each do |post| %>
<div class="post">
<h3><%= link_to(post.title, post_url(post)) %></h3>
<%= textilize(post.body_text) %>
</div>
<% end %>
Yes, there’s Ruby in there. There are data objects and method calls and loops.
If we were feeling particularly naughty we might throw some conditional logic in
there too. The point is, the above is not evil because it’s presentation logic.
If I had a line above this saying <% @posts = Post.find(:all, :conditions =>
... , :order => ... , :limit => ... ) %>
then that would be bad, in the same
way that using link_to
in a controller or a model doesn’t make much sense.
You need a programming language of some sort in your templates, otherwise how are you going to display the data your application has cooked up for you? (I’ve tried using ITX with PHP sites and that is not the way to do things. Making your controller explicitly do variable substitution and looping on your template is plain messy and repetitive, and couples the view and controller together too tightly with loads of variable names.) And, given that writing a templating language on top of the base language is only going to slow things down, you might as well let the base language of the app be your template language.
Anyone that can find me a serious, professional web designer who would be scared off by the above example or break it horribly can have a shiny gold medal. The only programming code a template should contain is variable substitution, formatting, looping and maybe some conditional statements, and I’d be happy letting any web designer worth paying write such code. People need to let go of the idea that you can’t embed a full-on scripting language in templates in case people abuse it: it’s insulting to template authors, and if you’re the sort of person that could abuse it, you ought to know better anyway.