SoFunction
Updated on 2025-04-14

Detailed functions and sample code of html/template module in Go language

Go languagehtml/templateModules are template engines designed for generating secure HTML output, supporting automatic escape to prevent XSS attacks. The following are the core methods and usage examples of this module:

1. Basic template analysis and rendering

and

Parses template strings and renders data.

package main

import (
    "html/template"
    "os"
)

func main() {
    // Define template string    tmplStr := `<h1>{{.Title}}</h1><p>{{.Content}}</p>`

    // parse template    tmpl, err := ("page").Parse(tmplStr)
    if err != nil {
        panic(err)
    }

    // Define data    data := struct {
        Title   string
        Content string
    }{
        Title:   "Welcome Page",
        Content: "This is safely rendered!",
    }

    // Render and output to standard output    err = (, data)
    if err != nil {
        panic(err)
    }
}

Output result

<h1>Welcome page</h1><p>This is what is safe to render!</p>

2. Load the template from the file

Load templates from multiple files, support template inheritance and nesting.

// File: templates/{{ define "header" }}<header>{{.SiteName}}</header>{{ end }}

// File: templates/{{ define "page" }}
<!DOCTYPE html>
<html>
  {{ template "header" . }}
  <body>
    <h1>{{.Title}}</h1>
  </body>
</html>
{{ end }}
func main() {
    // parse multiple template files    tmpl, err := (
        "templates/",
        "templates/",
    )
    if err != nil {
        panic(err)
    }

    // Render data    data := struct {
        SiteName string
        Title    string
    }{
        SiteName: "My website",
        Title:    "Homepage",
    }

    // Specify rendering using the "page" template    err = (, "page", data)
}

Output result

<!DOCTYPE html>
<html>
  <header>My website</header>
  <body>
    <h1>Home page</h1>
  </body>
</html>

3. Automatic escape and secure content

Automatically escape XSS content

By default, all variable contents are escaped.

data := struct {
    UserInput string
}{
    UserInput: "<script>alert('xss')</script>",
}

tmplStr := `<div>{{.UserInput}}</div>`
tmpl, _ := ("test").Parse(tmplStr)
(, data)

Output result

<div>&lt;script&gt;alert(&#39;xss&#39;)&lt;/script&gt;</div>

Trust the original HTML

useType tag security content.

data := struct {
    SafeContent 
}{
    SafeContent: ("<b>Bold text</b>"),
}

tmplStr := `&lt;div&gt;{{.SafeContent}}&lt;/div&gt;`
tmpl, _ := ("test").Parse(tmplStr)
(, data)

Output result

&lt;div&gt;&lt;b&gt;Bold text&lt;/b&gt;&lt;/div&gt;

4. Custom template functions

Funcs and

Register custom functions into the template.

func main() {
    // Define custom functions    funcMap := {
        "safeHTML": func(s string)  {
            return (s)
        },
    }

    // Create templates and register functions    tmplStr := `&lt;div&gt;{{. | safeHTML}}&lt;/div&gt;`
    tmpl := ("test").Funcs(funcMap)
    tmpl, _ = (tmplStr)

    // Render data    (, "<em>Italic text</em>")
}

Output result

&lt;div&gt;&lt;em&gt;Italic text&lt;/em&gt;&lt;/div&gt;

5. Conditional judgment and cycle

if and range grammar

Implement logical control in templates.

data := struct {
    ShowHeader bool
    Items      []string
}{
    ShowHeader: true,
    Items:      []string{"Go", "Python", "Java"},
}

tmplStr := `
{{ if .ShowHeader }}&lt;h1&gt;List&lt;/h1&gt;{{ end }}
&lt;ul&gt;
{{ range .Items }}
  &lt;li&gt;{{ . }}&lt;/li&gt;
{{ end }}
&lt;/ul&gt;
`

tmpl, _ := ("list").Parse(tmplStr)
(, data)

Output result

&lt;h1&gt;List&lt;/h1&gt;
&lt;ul&gt;
  &lt;li&gt;Go&lt;/li&gt;
  &lt;li&gt;Python&lt;/li&gt;
  &lt;li&gt;Java&lt;/li&gt;
&lt;/ul&gt;

6. Nested templates and block definitions

define and template directives

Reuse template fragments.

// Define the base templatetmplStr := `
{{ define "layout" }}
&lt;!DOCTYPE html&gt;
&lt;html&gt;
  &lt;head&gt;{{ template "title" }}&lt;/head&gt;
  &lt;body&gt;{{ template "content" . }}&lt;/body&gt;
&lt;/html&gt;
{{ end }}

{{ define "title" }}&lt;title&gt;Default title&lt;/title&gt;{{ end }}

{{ define "content" }}&lt;p&gt;Default content&lt;/p&gt;{{ end }}
`

// Cover some blockscustomTmplStr := `
{{ define "content" }}&lt;h1&gt;{{.Message}}&lt;/h1&gt;{{ end }}
`

// parse templatetmpl, _ := ("base").Parse(tmplStr)
tmpl, _ = (customTmplStr)

// Render datadata := struct{ Message string }{Message: "Custom content"}
(, "layout", data)

Output result

&lt;!DOCTYPE html&gt;
&lt;html&gt;
  &lt;head&gt;&lt;title&gt;Default title&lt;/title&gt;&lt;/head&gt;
  &lt;body&gt;&lt;h1&gt;Custom content&lt;/h1&gt;&lt;/body&gt;
&lt;/html&gt;

Summarize

  • Security: Automatically escape HTML special characters to prevent XSS attacks.
  • Core MethodsParseParseFilesExecuteFuncs
  • Advanced features
    • Nested templates (defineandtemplate)。
    • Conditions and loops (ifrange)。
    • Custom functions (Funcs)。
  • Applicable scenarios: Dynamically generate secure HTML pages, such as backend rendering of web applications.

This is the article about the detailed function introduction and sample code of the html/template module in Go language. For more related content of the html/template module, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!