Business logic in template files?

I've often heard and advocated for not "putting logic" in template files and having a separation of concerns.

The templates should be as simple to read and change as possible, and any complicated logic should be moved elsewhere.

There can be presentational logic - such as a simple if condition to determine if a value should be shown or looping over a list of items, but business logic should be within custom code - ideally within Service, Action or Command classes - and injected into the templates.

As well as making the templates simpler and cleaner, this logic can be tested separately with automated tests to ensure it works as expected. If the logic is within a template, this can be done for some things using Functional tests, such as whether some text appears on a page, but testing whether it appears in a certain order, for example, is much harder. This is best done within kernel or unit tests.

As well as being more testable, extracting the logic from a template makes it more reusable. You can use a service from multiple places within your website without duplicating it, making your website code smaller and easier to maintain.

- Oliver

Was this interesting?

Sign up here and get more like this delivered straight to your inbox every day.

About me

Picture of Oliver

I'm an Acquia-certified Drupal Triple Expert with 17 years of experience, an open-source software maintainer and Drupal core contributor, public speaker, live streamer, and host of the Beyond Blocks podcast.