La Famille / Field notes
Template Loading and Execution Revamp Report
Issue Addressed
The previous rendering logic in internal/render/render.go used a flawed pattern for parsing and executing Go html/templates:
- Templates were parsed repeatedly using
template.ParseFileson every page render, leading to unnecessary disk I/O and potential state leaking. - The
Executemethod was called on the template set without explicitly naming the root template. SinceParseFilesassociates the resulting template set with the base filename of the first file parsed, callingExecutecould render the wrong template depending on the order of files parsed.
Solution Implemented
The internal/render package has been refactored to use a lazy-loading Renderer struct containing a template cache.
- Lazy Caching: A
map[string]*template.Templateguarded by async.Mutexcaches parsed templates based on their file paths.template.ParseFilesis now only invoked once per unique layout file perRendererlifecycle. - Execution Isolation: To prevent per-page state bleed or corruption, the cached template is cloned via
template.Must(tmpl.Clone())for each page execution. - Addressing the Name Trap: The execution call has been updated from
clonedTmpl.Execute(...)toclonedTmpl.ExecuteTemplate(outFile, filepath.Base(templatePath), p). By explicitly providing the base filename of the intended root template, we guarantee that the correct layout is rendered regardless of the order in which partials were parsed. - Integration:
internal/generator/generator.gowas updated to instantiate a newRendererviarender.New()at the beginning of eachBuildcall. This keeps the cache scoped to a single build run, naturally side-stepping invalidation issues during watch mode.
Testing
The test coverage in internal/render/render_test.go has been significantly expanded:
TestHTML: The existing regression test was preserved and updated to use the newRenderer.TestHTMLLayoutSelection: A new table-driven test was added covering three distinct scenarios:- No Layout Specified: Verifies that pages fall back to the default
config.yamltemplate. - Layout Specified: Verifies that pages use the explicitly defined layout file (e.g.,
custom.html). - Back-to-back Renders: Renders two different pages sequentially using the same
Rendererinstance to verify that layouts are rendered correctly without cross-contamination.
- No Layout Specified: Verifies that pages fall back to the default
All tests, including go vet, pass successfully.