Documentation menu

Partials

A partial handles an HTTP request and returns an HTML fragment. It can also set response headers, for example to redirect an htmx request.

Place this handler in partials/time.go.

Copy
 1package partials
 2
 3import (
 4	"time"
 5
 6	"github.com/franchb/htmgo/framework/v2/h"
 7)
 8
 9func CurrentTimePartial(ctx *h.RequestContext) *h.Partial {
10	return h.NewPartial(
11		h.Pf("The current time is %s", time.Now().Format(time.RFC3339)),
12	)
13}

htmgo automatically registers exported handlers that accept a single named *h.RequestContext and return *h.Partial.

The generated route uses the module, package import path, and function name. Pass the function to h.GetPartial or h.PostPartial to generate the matching URL.

Polling a partial

Put this page in pages/time.go in the starter project. It uses the starter's RootPage helper, which loads htmgo.js. If you chose a different module name, update the myapp/partials import to match your go.mod.

Copy
 1package pages
 2
 3import (
 4	"github.com/franchb/htmgo/framework/v2/h"
 5
 6	"myapp/partials"
 7)
 8
 9func CurrentTimePage(ctx *h.RequestContext) *h.Page {
10	return RootPage(
11		h.Div(
12			h.GetPartial(partials.CurrentTimePartial, "load, every 1s"),
13		),
14	)
15}

The page requests the partial on load and again every second. htmx swaps the returned HTML into the div.

This hosted preview uses your browser clock. The code above polls a server.
The current time is