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

How to Call Go Methods from HTML Templates?

Barbara Streisand
Release: 2024-12-17 10:02:25
Original
846 people have browsed it

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

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

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

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!

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