A piggy bank of commands, fixes, succinct reviews, some mini articles and technical opinions from a (mostly) Perl developer.

Why shouldn't you put logic in the template?

The overall reason for keeping business logic separate from presentation is well known, see MVC.

Here are the practical reasons why putting business logic in the template is a really bad idea:
  • You can't re-use it
  • You can't unit test it
  • You can't log
  • You can't validate parameters to subroutines
  • You often can't create subroutines at all (and you shouldn't)
  • You can't use an IDE to look up method definitions
  • You can't "use strict"
  • You can't run a code tidier
  • You can't validate syntax
  • Error messages are different
  • Keyword behaviour can be subtly different, leading to the worst kind of bug - the one you don't notice until it's too late.
  • Now you have two languages to maintain instead of one
Logic which relates directly to the display of the page is borderline okay, although for the reasons stated above it's better to put as much of that as possible in a class/module, which could be called a View Model.

Corollary - don't pass the entire model to the template, only stash what is needed. Reasons for this:

  • Separation of concerns - the template should be editable by a front-end dev without any knowledge of syntax to specify models
  • Performance may be poor - for example if the model opens a new database connection each time it's called


This article was written with Perl and Template Toolkit in mind.