Pages

Pages are the entry point of an htmgo application.

A simple page may look like:

Copy
 1// route will be automatically registered based on the file name
 2func HelloHtmgoPage(ctx *h.RequestContext) *h.Page {
 3	return h.NewPage(
 4		h.Html(
 5			h.HxExtension(h.BaseExtensions()),
 6			h.Head(
 7				h.Link("/public/main.css", "stylesheet"),
 8				h.Script("/public/htmgo.js"),
 9			),
10			h.Body(
11				h.Pf("Hello, htmgo!"),
12			),
13		),
14	)
15}
htmgo uses std http with chi router as its web server, *h.RequestContext is a thin wrapper around *http.Request. A page must return *h.Page, and accept *h.RequestContext as a parameter

Auto Registration

htmgo uses file based routing. This means that we will automatically generate and register your routes with chi based on the files you have in the 'pages' directory.

For example, if you have a directory structure like so below, it will get registered into chi router as follows:

index.go -> /index

users.go -> /users

users.$id.go -> /users/:id

Note: id parameter can be accessed in your page with ctx.Param("id")

You may put any functions you like in your pages file, auto registration will ONLY register functions that return *h.Page

Tips:

Generally it is it recommended to abstract common parts of your page into its own component and re-use it, such as script tags, including styling, etc.

Example:

Copy
 1func RootPage(children ...h.Ren) *h.Page {
 2	return h.NewPage(
 3		h.Html(
 4		h.HxExtension(h.BaseExtensions()),
 5		h.Head(
 6			h.Meta("viewport", "width=device-width, initial-scale=1"),
 7			h.Link("/public/main.css", "stylesheet"),
 8			h.Script("/public/htmgo.js"),
 9		),
10		h.Body(
11			h.Class("bg-stone-50 min-h-screen overflow-x-hidden"),
12			ui.NavBar(),
13			h.Fragment(children...),
14		),
15	  )
16   )
17}

Usage:

Copy
1func UserPage(ctx *h.RequestContext) *h.Page {
2	return base.RootPage(
3		h.Div(
4			h.Pf("User ID: %s", ctx.Param("id")),
5		),
6}

You need to then update htmgo.yml to exclude that file from auto registration

automatic_page_routing_ignore: ["pages/root.go"]
Copy
In this example, my root page is in a file called root.go in the pages dir, so I need to exclude it from auto registration, otherwise htmgo wil try to generate a route for it.