Guides

Templates Rendering

If you are familiar with the Django/Jinja2 style template syntax, it may not comfortable for you to get in touch with the Go style template, especially the template inheritence part. However, using Golf you can handle it like a charm. Let’s take a look at an example:

package main

import (
  "github.com/dinever/golf"
)

func homeHandler(ctx *golf.Context) {
  data := map[string]interface{}{
    "Title": "Hello World",
  }
  ctx.Loader("template").Render("index.html", data)
}

func main() {
  App := golf.New()
  App.View.SetTemplateLoader("template", "templates/")
  App.Get("/", homeHandler)
  App.Run(":9000")
}
<h1>{{ .Title }}</h1>

The first step is to indicate a template loader for App.View. The first argument is the name of the template loader, the second argument is the path of the template folder. Golf allows you to indicating multiple template loaders, e.g., one for the templates of admin panel and another one for the templates of front-end.

After the template loader is set, you can render templates inside the loader by calling ctx.Loader("loader_name").Render("file_name", data). Indicating a template loader before calling Render is necessary, otherwise, Golf can not find out the template file.