Views

Namespaced Views

Place templates for namespaced routes and controllers.

By Guillermo Alvarez - Published Updated

Namespace the route

Namespaced routes set a path prefix, route-name prefix, and view namespace:

func Draw(router *lazyroutes.Scope) {
    router.Namespace("admin", func(admin *lazyroutes.Scope) {
        admin.Get("/posts", posts.New, (*posts.Controller).Index)
    })
}

The route path is /admin/posts, and the route namespace is admin.

Place the view under the namespace

For an admin namespace, posts controller, and Index action, the default view lives here:

app/views/admin/posts/index.html.tpl

Example:

<h1>Admin posts</h1>
{{range .posts}}
  <a href="{{path_for "admin_post" .Param}}">{{.Title}}</a>
{{end}}

Namespaced rendering intentionally does not fall back to the non-namespaced controller view. Missing namespace templates should fail loudly.

Override the layout for a namespace

If the namespace needs a different layout, add it beside the default layouts:

app/views/layouts/admin/app.html.tpl

The ordinary controller action stays the same:

func (c *Controller) Index(_ http.ResponseWriter, _ *http.Request) error {
    c.Set("posts", c.posts.List())
    return nil
}