VOOZH about

URL: https://www.geeksforgeeks.org/go-language/templates-in-golang/

⇱ Templates in GoLang - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Templates in GoLang

Last Updated : 16 Jul, 2020
Template in Golang is a robust feature to create dynamic content or show customized output to the user. Golang has two packages with templates:
  • text/template
  • html/template
There are mainly 3 parts of a template which are as follows:

1. Actions

They are data evaluations, control structures like loops or functions. Actions are delimited by {{ and }} where the root element is shown up by using dot operator(.) within braces, {{.}}. These actions control how the final output will look. To place the value of a field of current struct object, prefix the field name by a dot operator(.) within curly braces like {{.FieldName}}. The data which is evaluated inside it is called pipeline.

2. Conditions

if-else construct can also be used within a template. For example, to execute a template only when the condition is true, we can use the following syntax:
{{if .condition}} temp_0 {{else if .condition}} temp_1 {{else}} temp_2 {{end}}
This will execute the first template, temp_0, if the first condition is true if the second condition holds true, then the second template, temp_1, will execute, else the third template, temp_2, will execute.

3. Loops

Iterations can also be used within a template using the range action. Syntax for looping within a template is:
{{range .List}} temp_0 {{else}} temp_1 {{end}}
Here List should be an array, map or slice which if has length 0, then template temp_1 will be executed, else it iterates through the elements on List. The input format for a template should be of a UTF-8-encoded format. Any other text outside is printed as it is to the standard output. The predefined variable os.Stdout refers to the standard output to print out the merged data. The Execute() function takes any value which implements the Writer interface and applies a parsed template to the specified data object. Example 1: Output:
Hello Vani, your marks are 94%!
The package template "html/template" provides same interface to the "text/template" but rather having a text output, it implements data-driven templates for generating HTML output. This HTML output is safe against any external code injection. Example 2: "index.html" file: "main.go" file: Output:
Comment

Explore