Goku

Golang Web Mvc Framework

View the Project on GitHub qleelulu/goku

View & ViewEngine

Views are the components that display the application’s user interface (UI)

To render a view, you can just return a ViewResut which implement the ActionResulter interface. just like this:

    goku.Controller("blog").
        Get("page", func(ctx *goku.HttpContext) goku.ActionResulter {
        blog := GetBlogByid(10)

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

        // or you can pass a struct to ViewModel
        // then you can use it in template
        // like this: { { .Model.Title } }
        // that same as blog.Title
        return ctx.View(blog)
    })

ctx.View() will find the view in these rules:

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

for example, ServerConfig.ViewPath is set to "views", and return ctx.View() in home controller’s about action, it will find the view file in this rule:

1. {ProjectDir}/views/home/about.html
2. {ProjectDir}/views/shared/about.html

if you want to return a view that specified view name, you can use ctx.Render:

    // it will find the view in these rules:
    //      1. /{ViewPath}/{Controller}/{viewName}
    //      2. /{ViewPath}/shared/{viewName}
    // if viewName start with '/',
    // it will find the view direct by viewpath:
    //      1. /{ViewPath}/{viewName}
    ctx.Render("viewName", ViewModel)

Custom ViewEngine

ViewEngine is for how to find the view file. To Custom a ViewEngine, just implement the ViewEnginer interface.

// ViewEnginer interface.
// For how to find the view file.
type ViewEnginer interface {
    // find the view and layout
    // if template engine not suppot layout, just return empty string
    FindView(vi *ViewInfo) (viewPath string, layoutPath string)
}

And then set it to the ServerConfig.ViewEnginer

// server config
var config *goku.ServerConfig = &goku.ServerConfig{
    Addr:           ":8888",
    ViewEnginer:    &YourViewEngine{}, // set here
}

func main() {
    rt := &goku.RouteTable{Routes: routes}
    s := goku.CreateServer(rt, nil, config)
    log.Fatal(s.ListenAndServe())
}

A simple ThemeViewEngine is show how to do this, just check it.