Skip to content

1. Getting Started

Matt Mc edited this page Jul 12, 2018 · 6 revisions

Getting started

Getting started is easy and consists of getting the package, initializing a Set with a path to the templates and then rendering your first template.

  1. Get the package
  $ go get -u github.com/CloudyKit/jet

You may also use your favorite tool to vendor the library (git-freeze, git submodule).

  1. Create a Set and specify the lookup directories
import (
    "os"
    "path/filepath"

    "github.com/CloudyKit/jet"
)

var View = jet.NewHTMLSet("./views")) // relative to the current working directory from where this code is run

// may also use an absolute path:
var root, _ = os.Getwd()
var View = jet.NewHTMLSet(filepath.Join(root, "views"))
  1. Create a layout and your first template
<!-- file: "views/layouts/application.jet" -->
<!DOCTYPE html>
<html>
  <head></head>
  <body>
    {{yield body()}}
  </body>
</html>

<!-- file: "views/home.jet" -->
{{extends "layouts/application.jet"}}
{{block body()}}
  <main>
    This content will be yielded in the layout above.
  </main>
{{end}}
  1. Execute the template. You'll be providing the template with variables (jet.VarMap), data (interface{}) and most importantly, an io.Writer for the template to be rendered into. Anything that conforms to that interface can be passed; examples include a simple bytes.Buffer, Gin's context.Writer, or http.ResponseWriter in the case of Goji or if you're using the standard library's http package.
templateName := "home.jet"
t, err := View.GetTemplate(templateName)
if err != nil {
    // template could not be loaded
}
var w bytes.Buffer // needs to conform to io.Writer interface (like gin's context.Writer for example)
vars := make(jet.VarMap)
if err = t.Execute(&w, vars, nil); err != nil {
    // error when executing template
}

Template execution is synchronous and w will contain the rendered template's content. We didn't have any variables or data in this simple example so the vars map was empty (can also just pass nil here), as was the data (last parameter). Learn more about loading and executing templates in Rendering Templates.

Now that you know the basics, go on to the syntax documentation and take a look at the built-in functions available to you in every template.

Clone this wiki locally