Documentation menu

Caching Components Per Key

Use h.CachedPerKey or one of its typed variants when the component's output varies by key. The key can be any comparable Go value, such as a product ID or a struct containing a product ID and locale.

Declare the wrapper at package scope. Its callback returns the key and a render function. The callback runs on each call, while the render function runs when the key is missing or expired.

Copy
 1var CachedProductCard = h.CachedPerKeyT(15*time.Minute, func(productID string) (string, h.GetElementFunc) {
 2	return productID, func() *h.Element {
 3		return h.Div(
 4			h.H3(h.TextF("Product %s", productID)),
 5			h.P(h.TextF("Generated at %s", time.Now().Format(time.RFC3339))),
 6		)
 7	}
 8})
 9
10func ProductPage(ctx *h.RequestContext) *h.Page {
11	return h.NewPage(
12		CachedProductCard(ctx.UrlParam("id")),
13	)
14}

In pages/products.$id.go, the page passes a product ID as its one argument to h.CachedPerKeyT. Requests for the same ID reuse that ID's cached HTML.

Use h.CachedPerKey for zero arguments, h.CachedPerKeyT for one, and h.CachedPerKeyT2, h.CachedPerKeyT3, or h.CachedPerKeyT4 for two to four. The key returned by the callback determines which HTML to reuse. For private data, authorize each request before reading from the cache, and include every value that affects who can see the rendered content in the key.

The default in-memory store coordinates misses for each key through GetOrCompute. Other backends implement that contract through custom cache stores.