Home >Backend Development >Golang >How Do I Call a Go Method from Within a Template?

How Do I Call a Go Method from Within a Template?

Barbara Streisand
Barbara StreisandOriginal
2024-12-08 13:30:11828browse

How Do I Call a Go Method from Within a Template?

Calling a Method from a Go Template

Consider the following code:

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

To use this method in an HTML template, you would typically expect syntax similar to the following:

{{ .Label() }}

However, in Go templates, the parentheses can be omitted:

{{ .Label }}

For instance, given the following code:

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"))
}

The template will generate the output:

This is Bob

As per the Go template documentation, you can invoke any method that returns a single value or two values, where the second value is an error. If the method returns an error, Execute will return the error and halt template execution.

The above is the detailed content of How Do I Call a Go Method from Within a Template?. 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