Views
Template Data And Helpers
Pass controller data to templates and use registered helper functions.
Set template data
Controllers pass data to templates with Set:
func (c *PostsController) Show(
_ http.ResponseWriter,
r *http.Request,
) error {
post, ok := c.posts.Get(r.PathValue("post_id"))
if !ok {
return lazycontroller.Error(http.StatusNotFound, fmt.Errorf("post not found"))
}
c.Set("title", post.Title)
c.Set("post", post)
return nil
}
The view reads those values by name:
<h1>{{.title}}</h1>
<article>{{.post.Body}}</article>
Use built-in helpers
lazyapp registers route, asset, form, and Turbo helpers:
<a href="{{path_for "posts"}}">Posts</a>
{{stylesheet "/styles.css"}}
{{importmap "/assets/importmap.json"}}
Helpers return ordinary strings or trusted fragments, depending on what the helper renders.
Register app helpers
Application helpers are passed to lazyapp.New:
func RegisterHelpers() map[string]any {
return map[string]any{
"read_time": ReadTime,
}
}
Wire them during startup:
func App() *lazyapp.App {
return lazyapp.New(lazyapp.Config{
Name: "sample_app",
Drawer: Draw,
Public: app.Public,
Views: app.Views,
Context: Context,
Helpers: lazyapp.Helpers{helpers.RegisterHelpers()},
})
}
Then call the helper from a template:
<p>{{read_time .post.Body}} min read</p>