SoFunction
Updated on 2025-04-05

Golang Template's operation guide to implementing custom functions

1. Basic usage

1.1 Create a simple template function

package main

import (
    "html/template"
    "os"
)

func main() {
    // Create custom function maps    funcMap := {
        "upper": ,
        "lower": ,
    }
    
    // Create templates and add functions    tmpl := ("test").Funcs(funcMap)
    
    // parse the template content    tmpl, err := (`
        Original string: {{.}}
        capital: {{upper .}}
        lower case: {{lower .}}
    `)
    
    if err != nil {
        panic(err)
    }
    
    // Execution template    err = (, "Hello, World!")
}

1.2 Template function with parameters

package main

import (
    "html/template"
    "os"
)

func main() {
    funcMap := {
        "add": func(a, b int) int {
            return a + b
        },
        "multiply": func(a, b int) int {
            return a * b
        },
    }
    
    tmpl := ("calc").Funcs(funcMap)
    tmpl, err := (`
        {{add 5 3}} = 8
        {{multiply 4 6}} = 24
    `)
    
    if err != nil {
        panic(err)
    }
    
    err = (, nil)
}

2. Advanced usage

2.1 Conditional judgment function

package main

import (
    "html/template"
    "os"
)

func main() {
    funcMap := {
        "isEven": func(n int) bool {
            return n%2 == 0
        },
        "ifThenElse": func(condition bool, a, b interface{}) interface{} {
            if condition {
                return a
            }
            return b
        },
    }
    
    tmpl := ("conditions").Funcs(funcMap)
    tmpl, err := (`
        {{range $i := .}}
            number {{$i}} yes: {{if isEven $i}}even{{else}}odd number{{end}}
            Another way to write: {{ifThenElse (isEven $i) "even" "odd number"}}
        {{end}}
    `)
    
    if err != nil {
        panic(err)
    }
    
    numbers := []int{1, 2, 3, 4, 5}
    err = (, numbers)
}

2.2 Format function

package main

import (
    "fmt"
    "html/template"
    "os"
    "time"
)

func main() {
    funcMap := {
        "formatDate": func(t ) string {
            return ("2006-01-02 15:04:05")
        },
        "formatPrice": func(price float64) string {
            return ("¥%.2f", price)
        },
    }
    
    tmpl := ("format").Funcs(funcMap)
    tmpl, err := (`
        Current time: {{formatDate .Time}}
        Product price: {{formatPrice .Price}}
    `)
    
    if err != nil {
        panic(err)
    }
    
    data := struct {
        Time  
        Price float64
    }{
        Time:  (),
        Price: 99.99,
    }
    
    err = (, data)
}

2.3 Slice operation function

package main

import (
    "html/template"
    "os"
)

func main() {
    funcMap := {
        "first": func(x []interface{}) interface{} {
            if len(x) > 0 {
                return x[0]
            }
            return nil
        },
        "last": func(x []interface{}) interface{} {
            if len(x) > 0 {
                return x[len(x)-1]
            }
            return nil
        },
        "slice": func(x []interface{}, start, end int) []interface{} {
            if start < 0 {
                start = 0
            }
            if end > len(x) {
                end = len(x)
            }
            return x[start:end]
        },
    }
    
    tmpl := ("slice").Funcs(funcMap)
    tmpl, err := (`
        Complete slice: {{.}}
        The first element: {{first .}}
        The last element: {{last .}}
        slice[1:3]: {{slice . 1 3}}
    `)
    
    if err != nil {
        panic(err)
    }
    
    data := []interface{}{1, 2, 3, 4, 5}
    err = (, data)
}

3. Practical Examples

3.1 HTML Secure Escape

package main

import (
    "html/template"
    "os"
)

func main() {
    funcMap := {
        "safe": func(s string)  {
            return (s)
        },
        "safeAttr": func(s string)  {
            return (s)
        },
    }
    
    tmpl := ("safe").Funcs(funcMap)
    tmpl, err := (`
        Normal text: {{.Text}}
        HTMLcontent: {{safe .HTML}}
        Attribute value: <div {{safeAttr .Attr}}></div>
    `)
    
    if err != nil {
        panic(err)
    }
    
    data := struct {
        Text string
        HTML string
        Attr string
    }{
        Text: "<b>text</b>",
        HTML: "&lt;b&gt;HTML&lt;/b&gt;",
        Attr: `style="color: red"`,
    }
    
    err = (, data)
}

3.2 Data filtering and conversion

package main

import (
    "html/template"
    "os"
    "strings"
)

func main() {
    funcMap := {
        "join": ,
        "split": ,
        "title": ,
        "filter": func(arr []string, f func(string) bool) []string {
            var result []string
            for _, v := range arr {
                if f(v) {
                    result = append(result, v)
                }
            }
            return result
        },
    }
    
    tmpl := ("filter").Funcs(funcMap)
    tmpl, err := (`
        Original array: {{.}}
        Joinresult: {{join . ","}}
        Splitresult: {{split "a,b,c" ","}}
        Titleresult: {{title "hello world"}}
        Filterresult: {{filter . (lambda "len" "gt" 3)}}
    `)
    
    if err != nil {
        panic(err)
    }
    
    data := []string{"apple", "banana", "orange", "pear"}
    err = (, data)
}

4. Best Practices

4.1 Template function organization

// template_funcs.go
package template

import "html/template"

// Create global function mapvar GlobalFuncMap = {
    // String operation    "upper":      ,
    "lower":      ,
    "title":      ,
    
    // Numerical operation    "add":        func(a, b int) int { return a + b },
    "subtract":   func(a, b int) int { return a - b },
    "multiply":   func(a, b int) int { return a * b },
    "divide":     func(a, b int) float64 { return float64(a) / float64(b) },
    
    // Date operation    "formatDate": func(t , layout string) string { return (layout) },
    "now":        ,
    
    // Slice operation    "first":      first,
    "last":       last,
    "slice":      slice,
    
    // Conditional operation    "isEven":     isEven,
    "ifThenElse": ifThenElse,
}

// Use in the applicationfunc main() {
    tmpl := ("page").Funcs(GlobalFuncMap)
    // ...Other operations}

4.2 Error handling

package main

import (
    "html/template"
    "os"
)

func main() {
    funcMap := {
        "divide": func(a, b int) (string, error) {
            if b == 0 {
                return "", ("The divisor cannot be zero")
            }
            return ("%.2f", float64(a)/float64(b)), nil
        },
    }
    
    tmpl := ("error").Funcs(funcMap)
    tmpl, err := (`
        {{with $result := divide 10 2}}
            result: {{$result}}
        {{else}}
            Calculation error
        {{end}}
    `)
    
    if err != nil {
        panic(err)
    }
    
    err = (, nil)
}

Summarize

1. Basic Principles

  • Keep the function simple and clear
  • Pay attention to type safety
  • Proper handling of errors
  • Avoid overly complex logic

2. Common uses

  • Text formatting
  • Data conversion
  • Conditional judgment
  • Collection operations
  • HTML Secure Processing

3. Performance considerations

  • Cache templates
  • Avoid repeated parsing
  • Use memory reasonably

This is the article about the operation guide for implementing custom functions of Golang Template. For more information about Go Template custom functions, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!