internal/godoc/dochmtl: refactor Render
Trust: Jonathan Amsterdam
Run-TryBot: Jonathan Amsterdam
@@ -63,6 +63,14 @@ type RenderOptions struct {
Limit int64 // If zero, a default limit of 10 megabytes is used.
}
+// templateData holds the data passed to the HTML templates in this package.
+type templateData struct {
+ RootURL string
+ *doc.Package
+ Examples *examples
+ NoteHeaders map[string]noteHeader
+}
+
// Render renders package documentation HTML for the
// provided file set and package.
//
@@ -75,6 +83,26 @@ func Render(ctx context.Context, fset *token.FileSet, p *doc.Package, opt Render
opt.Limit = 10 * megabyte
}
+ funcs, data := renderInfo(ctx, fset, p, opt)
+ p = data.Package
+ if experiment.IsActive(ctx, internal.ExperimentUnitPage) {
+ if p.Doc == "" &&
+ len(p.Examples) == 0 &&
+ len(p.Consts) == 0 &&
+ len(p.Vars) == 0 &&
+ len(p.Types) == 0 &&
+ len(p.Funcs) == 0 {
+ return safehtml.HTML{}, nil
+ }
+ }
+
+ h := htmlPackage(ctx)
+ tmpl := template.Must(h.Clone()).Funcs(funcs)
+ return executeToHTMLWithLimit(tmpl, data, opt.Limit)
+}
+
+// renderInfo returns the functions and data needed to render the doc.
+func renderInfo(ctx context.Context, fset *token.FileSet, p *doc.Package, opt RenderOptions) (map[string]interface{}, templateData) {
// Make a copy to avoid modifying caller's *doc.Package.
p2 := *p
p = &p2
@@ -118,20 +146,7 @@ func Render(ctx context.Context, fset *token.FileSet, p *doc.Package, opt Render
sourceLink := func(name string, node ast.Node) safehtml.HTML {
return linkHTML(name, opt.SourceLinkFunc(node), "Documentation-source")
}
-
- if experiment.IsActive(ctx, internal.ExperimentUnitPage) {
- if p.Doc == "" &&
- len(p.Examples) == 0 &&
- len(p.Consts) == 0 &&
- len(p.Vars) == 0 &&
- len(p.Types) == 0 &&
- len(p.Funcs) == 0 {
- return safehtml.HTML{}, nil
- }
- }
-
- h := htmlPackage(ctx)
- tmpl := template.Must(h.Clone()).Funcs(map[string]interface{}{
+ funcs := map[string]interface{}{
"render_short_synopsis": r.ShortSynopsis,
"render_synopsis": r.Synopsis,
"render_doc": r.DocHTML,
@@ -139,19 +154,14 @@ func Render(ctx context.Context, fset *token.FileSet, p *doc.Package, opt Render
"render_code": r.CodeHTML,
"file_link": fileLink,
"source_link": sourceLink,
- })
- data := struct {
- RootURL string
- *doc.Package
- Examples *examples
- NoteHeaders map[string]noteHeader
- }{
+ }
+ data := templateData{
RootURL: "/pkg",
Package: p,
Examples: collectExamples(p),
NoteHeaders: buildNoteHeaders(p.Notes),
}
- return executeToHTMLWithLimit(tmpl, data, opt.Limit)
+ return funcs, data
}
// executeToHTMLWithLimit executes tmpl on data and returns the result as a safehtml.HTML.
