Introduction to Action
The actions of the Go template are the commands embedded in the template, which need to be placed in two braces {{Action}} in the template. We have used an important action before: dot(.). It represents the data passed to the template.
Here is an official list of action s in the Go language where "Arguments" and "pipelines" represent the results of execution of the data
{{/* a comment */}} Comment, ignored when executed. You can have more than one line. Comments cannot be nested, and must start and end close to the delimiter, as shown here. {{pipeline}} pipeline The default text representation of the value of will be copied to the output. {{if pipeline}} T1 {{end}} If pipeline The value of empty,No output, otherwise output T1 Execution results. No change dot Value of. Empty Values include false,0,Arbitrarily nil Pointer or nil Interface, any 0-length array, slice, dictionary. {{if pipeline}} T1 {{else}} T0 {{end}} If pipeline The value of empty,output T0 Execute result, otherwise output T1 Execution results. No change dot Value of. {{if pipeline}} T1 {{else if pipeline}} T0 {{end}} For simplification if-else Chains, else action Can include another directly if;Equivalent to: {{if pipeline}} T1 {{else}}{{if pipeline}} T0 {{end}}{{end}} {{range pipeline}} T1 {{end}} pipeline The value of must be an array, slice, dictionary, or channel. If pipeline The value of 0 has a length and will not have any output. otherwise dot Set to each member element of an array, slice, dictionary, or channel and execute T1; If pipeline The value of the is a dictionary, and the basic type of keys that can be sorted, elements are also sorted in the order of keys. {{range pipeline}} T1 {{else}} T0 {{end}} pipeline The value of must be an array, slice, dictionary, or channel. If pipeline Value of 0, does not change dot Value of and execute T0;Otherwise it will be modified dot And execute T1. {{template "name"}} Execution Name name Template, the parameters provided to the template are nil,If the template does not exist, the output is"" {{template "name" pipeline}} Execution Name name Template, the parameters provided to the template are pipeline Value of. {{with pipeline}} T1 {{end}} If pipeline by empty No output, otherwise the dot Set to pipeline Value of and execute T1. Do not modify the outside dot. {{with pipeline}} T1 {{else}} T0 {{end}} If pipeline by empty,No change dot And execute T0,otherwise dot Set to pipeline Value of and execute T1.
action role: action can complete process control, cycle, template and other operations. Simple logic processing can be done in a template by using actions (complex logic processing should be done in go, and data passed to the template should be processed)
Following is an example of several common actions.
1. Conditional Action
Conditional actions are very common and can be performed by determining whether conditions are met or not.
1.1 Format:
Conditional actions can be implemented in two formats.
Format 1:
{{ if arg}} Content to display {{ end }}
Format 2:
{{ if arg}} Content to display {{else}} When if Content to display when conditions are not met {{ end }}
The arg in the above format is a parameter passed to a conditional action, which can be a string constant, a variable, a function fetch method that returns a single value, and so on.
1.2 Example
Page Code:
<html> <head> <title>template file</title> <meta charset="utf-8"/> </head> <body> <!-- Embedded Action --> {{if .}} It's time to submit your notes {{else}} Your notes have not been written yet {{end}} </body> </html>
Processor code:
func handler(w http.ResponseWriter, r *http.Request) { //Parse Template File t := template.Must(template.ParseFiles("hello.html")) //Declare a variable age := true //Execution Template t.Execute(w, age) }
2. Iterative Action
Iteration actions can iterate over arrays, slices, maps, or channels.
2.1 Format
Format 1:
{{range . }} The elements traversed are {{ . }} {{ end }}
Format 2:
{{range . }} The elements traversed are {{ . }} {{ else }} No elements {{ end }}
In the format, the point after the range represents the traversed element; The point inside the content to be displayed represents the traversed element.
2.2 Example
Web-side code
<html> <head> <title>template file</title> <meta charset="utf-8"/> </head> <body> <!-- Embedded Action --> {{range .}} <a href="#">{{.}}</a> {{else}} Nothing traversed {{end}} </body> </html>
Processor code:
func handler(w http.ResponseWriter, r *http.Request) { //Parse Template File t := template.Must(template.ParseFiles("hello.html")) //Declare a String Slice stars := []string{"Li Da", "Li Er", "Pluggy Eggs"} //Execution Template t.Execute(w, stars) }
2.3 Description
- If the iteration is followed by one structure after another, get the field values in the structure using. Field name acquisition
{{range . }} Getting Structural Name Field name {{ .Name }} {{ end }}
- You can set variables when iterating over a Map, starting with $
{{ range $k , $v := . }} The key is {{ $k }} , Value is {{ $v }} {{ end }}
- Iterative Pipeline
{{ c1 | c2 | c3 }}
c1, c2, and c3 can be parameters or functions. Pipelines allow users to pass the output of one parameter to the next parameter, with | splitting between the parameters.
3. Set up actions
3.1 Format
Format One
{{ with arg }} The new value set for the incoming data is{{ . }} {{ end }}
arg is the new value set for the incoming data
Format 2
{{ with "" }} Because with Followed by an empty string, this part is not executed, execute else A Department equivalent to not modifying incoming data {{ else }} The data still came in{{ . }} {{ end }}
3.2 Example
Web-side code:
<html> <head><title>template file</title> <meta charset="utf-8"/> </head> <body> <!-- Embedded Action --> <div>The data is:{{.}}</div> {{with "Crown prince"}} <div>The data after replacement is:{{.}}</div> {{end}} <hr/> {{with ""}} <div>Look at the data now:{{.}}</div> {{else}} <div>Is the data not replaced or:{{.}}</div> {{end}} </body> </html>
Processor code:
func handler(w http.ResponseWriter, r *http.Request) { //Parse Template File t := template.Must(template.ParseFiles("hello.html")) //Execution Template t.Execute(w, "Civet") }
4. Include actions
Containing actions allows users to include another template in one template
4.1 Format
Format One
Do not pass data into the included template
{{ template "name" }}
Name is the name of the included template
Format 2
Pass-in data into the included template
{{ template "name" .}}
In action. The data to be passed to the containing template is also the data to be passed back to the current template in the background
4.2 Example
Web-side code 1:
<html> <head><title>template file</title> <meta charset="utf-8"/> </head> <body> <!-- Embedded Action --> <div>The data from the background is:{{.}}</div> <!-- Contain hello2.html Template --> {{ template "hello2.html"}} <div>hello.html End of File Content</div> <hr/> <div>take hello.html The data in the template file is passed to hello2.html Template file</div> {{ template "hello2.html" . }} </body> </html>
Web-side code 2:
<html> <head><title>hello2 template file</title> <meta charset="utf-8"/> </head> <body> <!-- Embedded Action --> <div>hello2.html The data in the template file is:{{.}}</div> </body> </html>
Processor code:
func handler(w http.ResponseWriter, r *http.Request) { //Parse Template File t := template.Must(template.ParseFiles("hello.html", "hello2.html")) //Execution Template t.Execute(w, "Test Inclusion") }
5. Define actions
When we visit some websites, we often see many pages with the same parts: navigation bar, copyright information, contact information and so on. These same layouts can be achieved by defining an action to define a template in a template file. The format for defining a template is to start with {{define "layout"} and end with {{end}}.
For the same department on each page, such as navigation bar, copyright information, etc., you can define an action by defining a template in a template file
5.1 Format
{{ define "arg" }} Here's the same department on the page {{ end }}
arg is the name of the template you defined, and you can include the currently defined template in other template files in the future by including actions
We can also define templates with the same name in different template files
5.2 Example
Define a template in a template file (hello.html)
<!-- Define Template --> {{ define "model"}} <html> <head><title>template file</title> <meta charset="utf-8"/> </head> <body> {{ template "content"}}</body> </html> {{ end }}
Then define multiple templates in a template file
<!-- Define Template --> {{ define "model"}} <html> <head><title>template file</title> <meta charset="utf-8"/> </head> <body> {{ template "content"}}</body> </html> {{ end }} {{ define "content"}} <a href="#">I'm surprised at something</a> {{ end }}
Processor code:
func handler(w http.ResponseWriter, r *http.Request) { //Parse Template File t := template.Must(template.ParseFiles("hello.html")) //Execution Template t.ExecuteTemplate(w, "model", "") }
6. Block Action
A block action is equivalent to defining a default template that will be used if it is not found
6.1 Format
```lua {{ block arg .}} If the name cannot be found in the template file arg Execute current content when template {{ end }}
6.2 Example
Web-side code:
<!-- Define Template --> {{ define "model"}} <html> <head><title>template file</title> <meta charset="utf-8"/> </head> <body> {{ block "content" .}}Show me if I can't find it {{ end }}</body> </html> {{ end }}
Processor-side code:
func handler(w http.ResponseWriter, r *http.Request) { rand.Seed(time.Now().Unix()) var t *template.Template if rand.Intn(5) > 2 { //Parse Template File t = template.Must(template.ParseFiles("hello.html", "content1.html")) } else { //Parse Template File t = template.Must(template.ParseFiles("hello.html")) } //Execution Template t.ExecuteTemplate(w, "model", "") }