Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

template

The HTML/Template package implements data-driven templates for generating safe HTML output against code injection.

Template syntax
{{...}}Copy the code

Template syntax is contained between {{and}}, where the dots in {{.}} represent the current object.

When we pass in a structure object, we can refer to To access the corresponding fields of the structure. Such as:

type UserInfo struct {
Name   string
Gender string
Age    int
}

func sayHello(w http.ResponseWriter, r *http.Request) {
    // Parse the specified file generation template object
    tmpl, err := template.ParseFiles("./hello.html")
    iferr ! =nil {
        fmt.Println("create template failed, err:", err)
        return
    }
    user := UserInfo{
        Name:   "Dry vine",
        Gender: "Male",
        Age:    18,}// Render the template with the given data and write the result to w
    tmpl.Execute(w, user)
}
Copy the code

. Represents the current object/structure user (w is just a variable on the server side that also holds the user structure)

<body>
<p>Hello {{.Name}}</p>
<p>Gender: {{. Gender}}</p>
<p>. Age: {{Name}}</p>
</body>
Copy the code
Template annotation
{{/* a comment */}} You can have multiple lines. Comments cannot be nested and must start and end with a delimiter.Copy the code
Piping pipeline

Go the template syntax support the use of pipe symbol | link multiple commands, usage and Unix pipelines under similar: | command will result in front of (or return values) is passed to a command after the last position.

Actions

The following actions basically include the actions and meanings commonly used in golang templates

{{/* a comment */}} comments, which are ignored during execution. You can have multiple lines. Comments cannot be nested and must start and end with delimiters, as shown here. The default text representation of the pipeline value is copied to the output. {{ifPipeline}} T1 {{end}} If pipeline is empty, no output is generated, otherwise T1 execution results are printed. Do not change the value of dot. The Empty value includingfalse,0And anynilA pointer ornilInterface, any length is0Array, slice, dictionary of. {{if pipeline}} T1 {{else}} T0 {{end}} output T0 if pipeline value is empty, otherwise output T1. Do not change the value of dot. {{if pipeline}} T1 {{else ifPipeline}} T0 {{end}} is used to simplifyif-elseThe chain,elseAn action can include another directlyif; Equivalent to: {{if pipeline}} T1 {{else}} {{if pipeline}} T0 {{end}}{{end}}
{{rangePipeline}} T1 {{end}} Pipeline values must be arrays, slices, dictionaries, or channels. If the pipeline value has a length of0, there will be no output; Otherwise dot is set to each member of an array, slice, dictionary, or channel and T1 is executed. If the pipeline value is a dictionary and the key is a sortable base type, the elements will also be sorted by key order. {{range pipeline}} T1 {{elseT0 {{end}} pipeline value must be array, slice, dictionary, or channel. If the pipeline value has a length of0, do not change the value of dot and execute T0; Otherwise, dot is modified and T1 is executed. {{template"name"}} Executes a template named name, supplied with parameters asnilIf the template does not exist, the output is""
{{template "name"Pipeline}} executes a template named name and provides the template with the value of pipeline. {{with pipeline}} T1 {{end}} If pipeline is empty does not produce output, otherwise dot is set to the value of pipeline and T1 is executed. Do not modify the dot outside. {{with pipeline}} T1 {{else}} T0 {{end}} If pipeline is empty, do not change dot and execute T0, otherwise dot is set to pipeline value and execute T1.Copy the code
To compare
Eq If arg1 == arg2 returns true ne if arg1! Return true lt if arg1 < arg2 true LE if arg1 <= arg2 true GT if arg1 > arg2 true ge if arg1 >= arg2Copy the code
 {{eq arg1 arg2 arg3}}
Copy the code
Nested template
<! DOCTYPEhtml>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>tmpl test</title>
</head>
<body>

    <h1>Test the nested template syntax</h1>
    <hr>
    {{template "ul.html"}}
    <hr>
    {{template "ol.html"}}
</body>
</html>

{{ define "ol.html"}}
<h1>This is ol. HTML</h1>
<ol>
    <li>AA</li>
    <li>BB</li>
    <li>CC</li>
</ol>
{{end}}
Copy the code

The ul.html template is not in the current HTML document. You need to specify the loaded template page via template.parsefiles on the server side to use it.

func tmplDemo(w http.ResponseWriter, r *http.Request) {
tmpl, err := template.ParseFiles("./t.html"."./ul.html")
iferr ! =nil {
    fmt.Println("create template failed, err:", err)
    return
}
user := UserInfo{
    Name:   "Dry vine",
    Gender: "Male",
    Age:    18,
}
tmpl.Execute(w, user)
Copy the code