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
Release: 2024-12-08 13:30:11
Original
849 people have browsed it

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

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

{{ .Label() }}
Copy after login

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

{{ .Label }}
Copy after login

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

The template will generate the output:

This is Bob
Copy after login

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!

source:php.cn
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