Theme Development Best Practices
What this domain covers
This domain tests maintainability and correctness: preprocess functions, render arrays, caching metadata, template organization, and avoiding anti-patterns. Questions reward the approach that keeps logic out of templates and cacheability intact.
Concepts to know
- Preprocess functions:
hook_preprocess_HOOK()prepares variables before rendering. Prefer these over logic in Twig. - Render arrays: structured arrays with
#theme,#markup,#attributes, and cache metadata. They are the canonical way to build output in modules and themes. - Cacheability metadata:
#cachewithcontexts,tags, andmax-age. Omitting contexts causes incorrect caching across users or routes. - Libraries: attach CSS/JS via
attach_library()or#attached, not hardcoded<link>tags. - Template organization: one template per component, named per convention, with minimal nesting.
- Accessibility and semantics: use proper landmarks and heading order in templates.
Traps in questions
A frequent trap is putting business logic in Twig instead of preprocess. Another is forgetting cache contexts when output varies by user role or URL, leading to leaked cached content. Questions may also suggest hardcoding asset paths in templates - the correct answer is a library attachment. Watch for #markup used where a render array with cache metadata is required.
Rule of thumb
Keep templates dumb: they print variables prepared by preprocess or render arrays. If output varies by anything (user, route, config), declare the corresponding cache context or tag.
Worked example: To show a personalized greeting, build a render array with #markup and #cache => ['contexts' => ['user']]. Without the user context, the greeting may be cached and shown to the wrong visitor.