Creating a custom Twig function
If you’ve arrived at this chapter after reading the preceding ones, it should be clear that any business logic that doesn’t depend upon a specific layout must not be put in a theme.
Although preprocess functions seem like they would be helpful to alter your data just before it is merged with a template, they have some issues:
- Tying the business logic to a specific theme will complicate the change to a new theme
- Altering data that is in a preprocess function can be inefficient because Drupal has already computed the data you’re changing
As we saw in Chapter 9, Styling Blocks, you can use different techniques to extract the fields of an entity:
- Read field values directly from the entity
- Use a preprocess function
- Define a bundle class to expose the entity’s fields
The first two approaches are challenging to be used on different websites. The last one is likely to only be applicable...