Goku

Golang Web Mvc Framework

View the Project on GitHub qleelulu/goku

Template

View Engine decide how to find the view file to render, and then pass to Template Engine parse and generate HTML.

Template Engine

goku.Controller("blog").
    Get("index", func(ctx *goku.HttpContext) goku.ActionResulter {

    // you can add any val to ViewData
    // then you can use it in template
    // like this: { { .Data.SiteName } }
    ctx.ViewData["SiteName"] = "My Blog"

    blogs := GetBlogs()
    // or you can pass a struct to ViewModel
    // then you can use it in template
    // like this: { {range .Model} }  { { .Title } }  { {end} }
    return ctx.View(blogs)
})

The default template engine is golang’s html/template.

    <div>
        <h2>{ { .Data.SiteName } }</h2>
        <ul>
          { {range .Model} }
            <li id="blog-{ {.Id} }">
              { {.Title} }
            </li>
          { {end} }
        </ul>
    </div>

Layout

Goku will find layout in these rules:

1. /{ViewPath}/{Controller}/{layout}
2. /{ViewPath}/shared/{layout}

the default layout is layout.html, and you can change it in ServerConfig.Layout.

layout.html

    <!DOCTYPE html>
    <html>
    <head>
        <title>Goku</title>
        { { template "head" } }
    </head>
    <body>
      { { template "body" . } }
    </body>
    </html>

and in the view template, it will look like this:

    { {define "head"} }
        <!-- add css or js here -->
    { {end} }

    { {define "body"} }
        I'm main content.
    { {end} }

note the dot in { {template "body" .} } in layout , it will pass the ViewData to the sub template.

More Template Engine Support

if you want to use mustache template, check mustache.goku

Custom Template Engine

To Custom a Template Engine, just implement the TemplateEnginer interface.

type TemplateEnginer interface {
    // render the view with viewData and write to w
    Render(viewpath string, layoutPath string, viewData *ViewData, w io.Writer)
    // return whether the tempalte support layout
    SupportLayout() bool
    // template file ext name, default is ".html"
    Ext() string
}

For more detail, you can check mustache.goku, it will show you how to this.