Skip to content
Thanatat Tamtan edited this page Sep 23, 2023 · 9 revisions

Hime have 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 template.Root to lookup template when parsing.

Output

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

<h1>Hello, Hime</h1>

</div>

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

Clone this wiki locally