AppDividend
Latest Code Tutorials

Golang Template Example | Package Template in Golang

0

The package template implements data-driven templates for generating textual output. To generate HTML output, see package html/template, which has the same interface as this package but automatically secures HTML output against specific attacks.

Golang template is a powerful method to customize output however you want, whether you’re creating the web page, sending an e-mail, working with Buffalo.

Golang Template

Content Overview

Before we get into this, it’s a perfect time to have a swift look at struct, array, and slice in Golang as these would be used quite a lot here.

Golang struct

Golang struct is the collection of fields and is defined with the type and “struct” keywords. See the following code example.

type Netflix struct {
	Show string
	Lead string
}

One thing to note that the above struct is visible outside the package it is in, as it starts with a capital letter.

Variables Show and Lead start with the capital letter and are also visible outside the package.

Go Struct fields are accessed using a dot. See the following complete example.

// hello.go

package main

import "fmt"

type Netflix struct {
	Show string
	Lead string
}

func main() {
	nflx := Netflix{
		Show: "Stranger Things",
		Lead: "Eleven",
	}
	fmt.Println("Netflix show", nflx)
}

Output

➜  hello go run hello.go
Netflix show {Stranger Things Eleven}
➜  hello

Golang Array

Golang programming language provides the data structure called an array, which can store the fixed-size sequential collection of elements of the same type.

An array is used to store the collection of the data, but it is often more useful to think of an array as the collection of variables of the same type.

In Go, an array is the numbered sequence of elements of a specific length. See the following code.

package main

import "fmt"

func main() {
	var a [5]int
	a[0] = 18
	a[1] = 19
	a[2] = 21
	a[3] = 29
	a[4] = 46
	fmt.Println(a)
}

Output

➜  hello go run hello.go
[18 19 21 29 46]
➜  hello

We have created an array that will hold precisely 5 ints.

The type of items and length are both parts of the array’s type.

By default, the array is zero-valued, which for ints means zeros.

In the above code, the var a[5]int declares the integer array of length 5. 

All items in the array are automatically assigned a zero value of the array type.

In this case, variable a is the integer array, and hence all items of a are assigned to 0, the zero value of the integer. An index of the array starts from 0 and ends with length – 1.

Golang Slice

A slice is a segment of the array.

Like arrays, slices are indexable and have the length. Unlike the arrays, this length is allowed to change. Here’s an example of a slice.

Okay, now let’s take an actual example and print the slice on the console.

package main

import "fmt"

func main() {
	var sl = []string{"Baby Yoda", "Mandalorian"}

	fmt.Println("Slice Example: ", sl)
}

Output

➜  hello go run hello.go
Slice Example:  [Baby Yoda Mandalorian]
➜  hello

Using Go Templates

Two packages ’re operating with templates.

  1. text/template
  2. html/template

Both provide the same interface; however, an html/template package is used to generate the HTML output safe against code injection.

text/template

The text/template package is designed to take text as input and output different text based on transforming the original text using the values of an object.

The input text for a template is UTF-8-encoded text in any format.

“Actions” which data evaluations or control structures–are delimited by “{{” and “}}”; all text outside actions is copied to the output unchanged. Except for raw strings, actions may not span newlines, although comments can.

Now, what is action in Template? Let’s find out.

Actions in Template

Templates are provided to the appropriate functions either as a string or as “raw string”.

Actions represent the data evaluations, functions, or control loops. They’re delimited by {{ }}. Other, non-delimited parts are left untouched.

Data evaluations

When using templates, you will bind them to some data structure (e.g., struct) from which you’ll obtain data.

We can obtain the data from a struct by using the {{ .FieldName }} action, which will replace it with FieldName value of the given struct, on parse time.

Then the struct is given to the Execute function.

There’s also a {{ . }} action that you can refer to the value of non-struct types.

Parsing Templates in Golang

There are three most important and most frequently used functions are:

  1. New: It allocates new, undefined template,
  2. Parse: It parses given template string and returns parsed template,
  3. Execute: It applies a parsed template to the data structure and writes the result to the given writer.

Now, let’s see the full code of the text/template program.

// hello.go

package main

import (
	"os"
	"text/template"
)

type Netflix struct {
	Show string
	Lead string
}

func main() {
	net := Netflix{"Stranger Things", "Eleven"}

	t, err := template.New("net").Parse("Number one show \"{{ .Show}}\" has: \"{{ .Lead}}\"")
	if err != nil {
		panic(err)
	}
	err = t.Execute(os.Stdout, net)
	if err != nil {
		panic(err)
	}
}

Output

➜  hello go run hello.go
Number one show "Stranger Things" has: "Eleven"                                 
➜  hello

As you can see in the output, templates provide a powerful way to customize the textual output.

text/html

Golang’s html/template package provides the rich templating language for HTML templates.

It is mostly used in web applications to display data in a structured way in a client’s browser.

One great benefit of Golang’s templating language is the automatic escaping of data.

There is no need to worry about XSS attacks as Golang parses an HTML template and escapes all inputs before displaying it to the browser.

Writing the template in Go is very simple. When rendering templates, the data passed in can be any Go’s data structure.

It may be a simple string or a number, and it can even be a nested data structure.

We can access the data in a template, the topmost variable is accessed by {{ . }}.

The dot inside the curly braces is called the pipeline and the root element of the data.

See the following code.

// hello.go

package main

import (
	"html/template"
	"os"
)

type Mandalorian struct {
	Name string
}

func main() {
	t := template.New("fieldname example")
	t, _ = t.Parse("hello {{.Name}}!")
	mando := Mandalorian{Name: "Baby Yoda"}
	t.Execute(os.Stdout, mando)
}

Output

➜  hello go run hello.go
hello Baby Yoda!                                                                
➜  hello

The package template (html/template) implements the data-driven templates for generating HTML output safe against code injection.

It provides the same interface as the package text/template and should be used instead of text/template whenever the output is HTML.

Example of html/template in Golang

See the following code.

// hello.go

package main

import (
	"html/template"
	"log"
	"os"
)

func main() {
	const tpl = `
<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>{{.Title}}</title>
	</head>
	<body>
		{{range .Items}}<div>{{ . }}</div>{{else}}<div><strong>no rows</strong></div>{{end}}
	</body>
</html>`

	check := func(err error) {
		if err != nil {
			log.Fatal(err)
		}
	}
	t, err := template.New("webpage").Parse(tpl)
	check(err)

	data := struct {
		Title string
		Items []string
	}{
		Title: "Disney plus Programs",
		Items: []string{
			"The Mandalorian",
			"Avengers Endgame",
		},
	}

	err = t.Execute(os.Stdout, data)
	check(err)

	noItems := struct {
		Title string
		Items []string
	}{
		Title: "Upcoming Programs",
		Items: []string{},
	}

	err = t.Execute(os.Stdout, noItems)
	check(err)

}

Output

➜  hello go run hello.go

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>Disney plus Programs</title>
	</head>
	<body>
		<div>The Mandalorian</div><div>Avengers Endgame</div>
	</body>
</html>
<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>Upcoming Programs</title>
	</head>
	<body>
		<div><strong>no rows</strong></div>
	</body>
</html>

Finally, Golang Template Example | Package Template in Golang article is over.

Related Posts

Golang slice extend()

Golang for loop

Golang maps example

Install Go on Mac

Go Functions Example

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.