The best templating system in Go

Jet templates. A library that makes working with templates in Go much easier.

I really don't like working with built-in templates in Go. Writing maps, inconvenient work in the templates themselves. Jet solves this.

Data transfer

To create a map with data for a template, you only need to write one line:

data := make(jet.Varmap)

And in order to write something there, you need to write like this:

data.Set("data", any)

Now about how to use it:

Render template

views := jet.NewHTMLSet(pathToTemplates) // Получаем абсолютно все шаблоны по 
										 // этому пути

To render a specific template, you need to write this:

t, err := tc.GetTemplate(templateName) // Получаем определенный шаблон

// обработка ошибки

err = t.Execute(w, data, nil) // где w - ResponseWriter, data - jet.Varmap с данными.

It is important here that the data must be placed in the second place in the arguments, not in the third, although the name of the third argument is called “data”, it must be placed on “variables”

But, if necessary, you can write your own structure with data and then put it in third place:

data := struct {
		Data string
	}{
		Data: "hello",
	}
err = t.Execute(w, nil, data)

Here is the simplest example of using jet:

package main

import (
	"log"
	"net/http"

	"github.com/CloudyKit/jet"
)

func main() {
	http.HandleFunc("/hello", func(w http.ResponseWriter, r *http.Request) {
		set := jet.NewHTMLSet("./templates")

		data := make(jet.VarMap)

		t, err := set.GetTemplate("hello.html")
		if err != nil {
			log.Fatal(err)
		}

		data.Set("message", "Hello World!")

		t.Execute(w, data, nil)
	})

	log.Fatal(http.ListenAndServe(":8080", nil))
}

Processing should take place in the http handler, but it can be moved to a separate “render” package and the necessary data can be transferred there like “w ResponseWriter, data jet.Varmap, templateName string” and then called from the handler.

I use the built-in “ResponseWriter” in the standard net/http package, but I don’t know how it’s done in GoFiber, I think it should be in its fiber.Ctx

Template syntax

There is a lot to talk about, so if you need to, read here: https://github.com/CloudyKit/jet/wiki/3.-Jet-template-syntax

I'll start with using the data that was transmitted

Acceptance of data

Let's say we have data with message equal to “Hello World!”

data.Set("message", "Hello World!")

Now in the template, in double curly brackets, we write the name of the variable that we wrote in data:

<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title></title>
    <link href="https://habr.com/ru/articles/837430/css/style.css" rel="stylesheet" />
  </head>
  <body>
    <div>{{message}}</div>
  </body>
</html>

Our page:

Page in browser

Page in browser

But let's imagine that you wanted to use the structure you wrote yourself:

data := struct {
		Data string
	}{
		Data: "hello",
	}
err = t.Execute(w, nil, data)

Then in the template, to get the data of the Data field from the structure, you need to add a dot at the beginning:

<div>{{.Data}</div>

Cycles

To iterate over the array you passed to the template, you can use “range”:

{{range keyOrIndex, value := array}}
Ваши действия
{{end}}

But, you can do without the index:

{{range value := array}}
Ваши действия
{{end}}

I'll say even more, you can remove everything and leave only the array:

{{range array}}
<p>Выводим текущий элемент: {{.}}</p>
{{end}}

Layouts

You can also easily work with layouts. To do this, you need to create a file with the contents of the layout, for example this one:

<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title></title>
    <link href="https://habr.com/ru/articles/837430/css/style.css" rel="stylesheet" />
  </head>
  <body>
    {{yield body()}}
  </body>
</html>

“yield” calls a piece of code from another file. Let’s now create another file with the contents of body():

{{extends "путь к вашему layout"}} 
{{block body()}}
<div>Что-то<div>
{{end}}

There can be an unlimited number of such files with body content. You can create other blocks and place them in another place, for example, not in the body, but in the title with the same name

Now, if you have many templates with the same beginning, you can put it all in the layout and connect from different files.

Conclusion

I hope you have discovered this wonderful library and it will become easier for you to write templates in Go. You can read this and much more in the official repository Jet templates: https://github.com/CloudyKit/jet/

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *