Documentation menu

Caching Components Globally

Use h.Cached to reuse a component's rendered HTML for a fixed duration. The first render computes and stores the HTML. Subsequent renders reuse that value until it expires.

Declare the wrapper at package scope so it can reuse the cache across requests. Cache only content that every caller can see.

Copy
1var CachedStatus = h.Cached(15*time.Minute, func() *h.Element {
2	return h.P(h.TextF("Generated at %s", time.Now().Format(time.RFC3339)))
3})
4
5func StatusPage(ctx *h.RequestContext) *h.Page {
6	return h.NewPage(
7		CachedStatus(),
8	)
9}

The timestamp remains the same until the cached value expires. Replace the callback with your own component to cache a shared render.

Use h.Cached for zero arguments, h.CachedT for one, and h.CachedT2, h.CachedT3, or h.CachedT4 for two to four. Each wrapper uses one cache entry for all calls, regardless of its arguments.

When the rendered output depends on an identifier, use per-key caching.