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
Release: 2024-12-14 10:18:12
Original
215 people have browsed it

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
}
Copy after login

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

{{ .Label }}
Copy after login

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"))
}
Copy after login

When you run this program, it will output:

This is Bob
Copy after login

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 of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template