Golang Template

Learn via video courses
Topics Covered

Overview

The golang template is a feature that is robust and is used for creating dynamic content or presenting a customized output to the end user. In this article, we will be covering all about the golang template.

Introduction

The golang template is a powerful way for customizing the output in a way that users want. Whether it's about creating a web page or sending an email or working with a command line interface for instance kubectl. In order to use the templates, there are two packages for the same, text/template and HTML/template. Both the packages provide the same interface but the HTML/template package is mostly used for generating an HTML output that is safe against the injected code.

Actions

Before learning about the implementation of the golang template, let’s deep dive into their syntax. The templates are mostly provided to the functions that are appropriate either as a string or as a raw string. The actions here represent the data evaluations, control loops, or functions. They are delimited by curly brackets, {{ }}. In this, the non-delimiter parts are left untouched.

Data Evaluations

These golang templates are usually used for binding the templates with any data structure for instance by using struct the data can be obtained. In order to obtain the information or data from a struct, the action {{ .FieldName }} can be used which helps replace the value FieldName of the struct given on the parse time. This struct is then passed on to the Execute function which is covered further in the article. There is also one more action, {{.}} which is used for referring a value of a non-struct data type.

Conditions

The if loops can also be used in the golang template. For instance, we can check if the FieldName is non-empty and if it is non-empty then prints its value. The expression looks like this: "{{if .FieldName}} Value of FieldName is {{ .FieldName }} {{end}}" The else and else-if are also supported by the Go language. The expression looks like this: {{if .FieldName}} // action {{ else }} // action 2 {{ end }}.

Loops

By using the action range, we can loop through the slice in the Go language. Here the range action is defined as follows: template {{range .Member}} ... {{end}}. If a slice is of type non-struct then we can refer to it by using the action {{ . }} for the value. In the case of structs, we can also refer to the value by using the action {{ .Member }}.

Functions, Pipelines, and Variables

The actions of golang have many in-built functions that can be used along with pipelines to parse the output. The pipelines in golang are annotated with the pipe | symbol and the default behavior of this is sending the data of the function from the left side to the right side. The functions sometimes are also used to escape the result of an action. There are many functions available for this by default, for example, HTML which is used for returning the escaped output of the HTML which is safe against code injection, or js which is used for returning javascript escaped output. Using the action with, we can define a variable that is available within the with block. The block is as follows: {{ with $x := <^>result-of-some-action<^> }} {{ $x }} {{ end }}.

Parsing Templates

The three important and most frequently used functions for parsing the templates are:

New

This allows new and undefined template The code given below shows the function mentioned which is ‘new’

Output

Output

As seen from the example, this template provides a way to customize the output. Besides customizing the textual output, we can also manipulate the HTML output by using the package, HTML/template.

Parse

It is used for parsing the given string of template and at the output, returns the parsed template.

Execute

This applies parsed template to the data structure and then writes the end result to the given writer

Verifying Templates

The package template provides the function Must which is used in templates for verifying if the given template is valid or not during the parsing. The function Must provide the same output like we would get if we do it manually for the error which can be seen in the previous example. By using this technique, we can save typing work but if any error is encountered the application will be unstable. In the case of advanced handling of error, it is easier if we use the Must function. This function takes templates and errors as an argument and a new function is provided as an argument to it.

Implementing Templates

In implementing templates, we will learn how to use the template by creating a an HTML page which is simple, along with the to-do list.

Creating Web Pages Using Templates

The package, HTML/template allows us to have a template file that can be in form of any language, for instance, an HTML file in order to make both, the backend as well as the frontend easier to develop. The data structure in the following example identifies as a to-do list that has a root element which is the user’s name as well as the list which is displayed as an array that contains structs along with the name of the task as well as the status.

This simple HTML page will display the name of the user and their to-do list. In order to build this, we will use the range action to iterate over a slice by using the with action which makes it easier to get the data from the slice and adds a condition that checks if the task is already done or not. If in case the task is completed, it will write yes in the appropriate field else it will write no in the field.

Like we did in the previous example, here we will parse the template and then apply it to the struct that contains the data. But instead of the parse function, here we will use the ParseFile.

Now we will use HTML/template instead of text/template. Since they both provide the same interface here we will use the exact same function to parse the template. Even if we use text/template, the output will remain the same with the difference that this time, the code is safe against the code injection. This template creates a code given below

Parsing Multiple Files

This approach is not suitable in cases when there are multiple files or when a developer is adding a new file and removing the old file. Besides a function ParseFile, there is a function called ParseGlob that takes the argument glob and then parses all the files that match the glob. Look at the code given below to understand this better

The following are the use cases of this approach:

  • This approach is generally used when we have to generate a web page that uses Go API for obtaining the data.
  • It can also be used for sending e-mails.
  • Lastly, we can also use it for creating a beautiful website.

Customizing Command’s Output

We can incorporate these templates in the CLI for allowing users to customize the command output. This is mostly done by providing the flags in order to input the templates. For instance, a Kubernetes CLI which is kubectl provides the following two flags, the first is the --template that provides the template as a string and the second is the template-file that provides a template in form of a file. Look at the example given below to understand this better

Similarly, this can be done by using the spf13/cobra. This code snippet removes the data that parse the logic. The users can use this for customizing the template language.

Conclusion

  • In the Go language, the template is a feature that is robust and is used for creating dynamic content or presenting a customized output to the end user.
  • The Go templates are a powerful way for customizing the output in a way that users want. Whether it's about creating a web page or sending an email or working with a command line interface for instance kubectl. In order to use the templates, there are two packages for the same, text/template and HTML/template. Both the packages provide the same interface but HTML/template package is mostly used for generating an HTML output that is safe against the injected code.