Home >Backend Development >Golang >How Do I Call Custom Methods from Go HTML Templates?

How Do I Call Custom Methods from Go HTML Templates?

Barbara Streisand
Barbara StreisandOriginal
2024-12-14 10:18:12203browse

How Do I Call Custom Methods from Go HTML Templates?

Calling Methods from Go Templates

In Go, you can define custom methods for data types. How do you call these methods from an HTML template in Go?

Consider the following example:

type Person struct {
  Name string
}
func (p *Person) Label() string {
  return "This is " + p.Name
}

To call the Label method from a template, use the following syntax:

{{ .Label }}

Note that you omit the parentheses when calling the method.

Here's a complete Go program that demonstrates the usage of method calls in templates:

package main

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

type Person string

func (p Person) Label() string {
    return "This is " + string(p)
}

func main() {
    tmpl, err := template.New("").Parse(`{{.Label}}`)
    if err != nil {
        log.Fatalf("Parse: %v", err)
    }
    tmpl.Execute(os.Stdout, Person("Bob"))
}

When you run this program, it will output:

This is Bob

According to the Go template documentation, you can call any method that returns one value (of any type) or two values if the second one is of type error. If the second returned value is an error, the Execute function will return that error as non-nil and discontinue the template execution.

The above is the detailed content of How Do I Call Custom Methods from Go HTML Templates?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn