Is it bad practice to pass services to thymeleaf templates?

Viewed 111

I have a Spring Boot application that relies on some quite complex logic to determine whether or not users have permission to perform certain actions. When rendering my templates though, I have to decide whether or not to show certain UI elements based on those permissions, and currently my only way to do that is to pass countless mayUserDo... attributes to the view model.

It would be much easier to instead pass a UserPermissionsService to my model, and perform those simple checks in the template by calling a method from that service, thereby avoiding the mess of having lots of redundant variables floating around.

So my question is: Is this an acceptable solution? If not, why not?

1 Answers

I would consider it a bad practice to call the services from your thymeleaf templates.

The templates job is to display data. The more logic you put into your templates, the harder your templates get to understand and to maintain.

Also think about testing: If your Service returns one DTO with all fields for one usecase, you can easily test the completeness and correctness of this object at once, instead of testing each method with the same requirements and not having the relation between the methods covered.

To solve your problem you could think about breaking your template into smaller parts and join them together. E.g. a header that stays constant could be extracted. If you have one "positive" and one "negative" case determine the access to multiple fields, this part could be extracted into a smaller template as well.

Related