When would I use a conditional in a template, rather than just use the conditional in the backend function calling this html file containing the template?
-
Hi Bob. I'd say the rule of thumb is "keep your templates concerned with rendering data only." Conditionals in the template should mainly be concerned with presenting the data your application passes in. Use a conditional in the template to display a "No items" message if a passed list is empty but avoid things that, say, trigger further database or external API calls. – chucksmash Jun 30 '19 at 22:55
1 Answers
This is somewhat of a question of philosophy, and as such borders on "Opinion-based," however I feel like there's a good treatise in here somewhere about separation of business logic from data.
Templates should contain data. That data might not be static, which is when you would use template conditionals. Your page might want to look different if it's being accessed by an unauthenticated user, or your page might want to allow the user to change date formats or etc.
Backend functions should do work. This is business logic, and the conditionals here should reflect that. It wouldn't be appropriate to query the user's session to see their locale and change the way data is formatted here -- that's not business logic that's UI logic. Conditionals here should effect database lookups, or API calls, or other things that might have farther-reaching side effects than "How the user perceives the data being presented."

- 52,157
- 12
- 73
- 112