Home >Backend Development >Golang >How to Call Go Methods from HTML Templates?

How to Call Go Methods from HTML Templates?

Barbara Streisand
Barbara StreisandOriginal
2024-12-17 10:02:25881browse

How to Call Go Methods from HTML Templates?

Calling Methods from Go Templates

In Go, you can define methods for custom types, allowing you to operate on those types in a more organized manner. When working with HTML templates, it's often useful to access these methods from within the template itself.

Question:

Consider the following:

type Person struct {
  Name string
}

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

How would you utilize the Label() method within an HTML template?

Answer:

To call a method from a Go template, simply omit the parentheses. In this case, the template would look like:

{{ .Label }}

This will call the Label() method and insert its return value into the template.

Here's a full example:

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

Additional Note:

According to the Go documentation, any method that returns one value of any type or two values, with the second being of type error, can be called from a template.

The above is the detailed content of How to Call Go Methods from 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