Business logic vs presentation logic

Inside a .theme file, there are a lot of php functions that you could use to alter the way Drupal works. However, it’s not because you can write functions inside a .theme file, that you should do it here. A lot of functions that you could write, fit better in a custom Drupal module. Only functions that impact the presentational layer should be used inside a .theme file. Functions that change something in the business logic, should go in to a custom module.

If you Google these concepts, you get some big words thrown at you about what the difference is between the 2 logics. Here is our stab at explaining it in a way actual humans (read: Frontenders) can understand.

An understandable example #

Let’s take an example, let’s say we used views to create a list of news-nodes for an overview page. We start styling these nodes, when we notice that the nodes are not sorted on the date that they were published. We don’t even see a date displayed on the node at all. So we start doing some changes to fix this:

  1. First, we add a publication date field to news-nodes. This new field saves a specific time with a timestamp.
  2. Then, we change the view so that it sorts on publication date.
  3. We add this new field to the teaser view-mode of news-nodes
  4. Lastly, we change how the datestamp looks, from a detailed 01/01/2019 16:30 to something like ‘2 days ago.

So in this example steps 1-2 are all steps that involve certain logic, and the last 2 steps are purely for aesthetics.

In the last 2 steps, we change how we present data, we are not changing that timestamp field in the database to store 2 days ago. We keep the field intact, but change how we want to show that information.

So whenever you want to write something in a .theme file, ask yourself first the question, if the change you want to do is merely presentational.