Skip to content
Thanatat Tamtan edited this page Jun 9, 2026 · 10 revisions

Hime has a built-in html/template loader and renderer.

package main

import (
	"log"

	"github.com/moonrhythm/hime"
)

func main() {
	app := hime.New()

	t := app.Template()
	t.Parse("index", `<h1>Hello, {{.Name}}</h1>`)

	app.Handler(hime.Handler(index))
	app.Address(":8080")
	err := app.ListenAndServe()
	if err != nil {
		log.Fatal(err)
	}
}

func index(ctx *hime.Context) error {
	return ctx.View("index", map[string]any{
		"Name": "Hime",
	})
}

Load template from files

<!-- template/index.tmpl -->
<h1>Hello, {{.Name}}</h1>
package main

import (
	"log"

	"github.com/moonrhythm/hime"
)

func main() {
	app := hime.New()

	t := app.Template()
	t.Dir("template")
	t.ParseFiles("index", "index.tmpl")

	app.Handler(hime.Handler(index))
	app.Address(":8080")
	err := app.ListenAndServe()
	if err != nil {
		log.Fatal(err)
	}
}

func index(ctx *hime.Context) error {
	return ctx.View("index", map[string]any{
		"Name": "Hime",
	})
}

Layout

<!-- layout.tmpl -->
{{define "root"}}
<!doctype html>
<title>Hime Example</title>
<div id="app">
	{{template "body" .}}
</div>
{{end}}
<!-- template/index.tmpl -->
{{define "body"}}
<h1>Hello, {{.Name}}</h1>
{{end}}
t := app.Template()
t.Dir("template")
t.Root("root")
t.ParseFiles("index", "index.tmpl", "layout.tmpl")

Use t.Root() to set the layout template to look up after parsing.

Output

<!doctype html>
<title>Hime Example</title>
<div id="app">

<h1>Hello, Hime</h1>

</div>

Custom functions

Register template functions with app.TemplateFunc / app.TemplateFuncs (available to every template) or t.Func / t.Funcs (on a single loader).

app.TemplateFunc("upper", strings.ToUpper)
<h1>{{upper .Name}}</h1>

Built-in functions

hime registers a few helpers on every template:

  • route — build a URL from a named Route
  • global — read a Global
  • param — build a query param for route
  • component — render a Component
  • dict — build a map to pass multiple values to a component or partial (html/template has no map literal)
  • json — marshal a value to JSON for an inline <script> (escapes <, >, &)
{{component "card" (dict "title" .Title "body" .Body)}}

<script>var state = {{json .State}}</script>

Load from embed.FS

Use t.FS to load templates from an embed.FS instead of from disk:

//go:embed template/*
var files embed.FS

t := app.Template()
t.FS(files)
t.Dir("template")
t.ParseFiles("index", "index.tmpl")

Next, see how to Minify Template, and how to use Preload to preload templates.

Clone this wiki locally