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

How to Call Go Methods from Within HTML Templates?

Barbara Streisand
Barbara StreisandOriginal
2024-12-25 05:59:12707browse

How to Call Go Methods from Within HTML Templates?

Accessing Go Methods from HTML Templates

In Go, templates are a versatile way to generate HTML content dynamically. However, calling methods from within templates can sometimes pose a challenge.

Problem:

Consider the following Go struct:

type Person struct {
  Name string
}

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

How can this method be accessed from an HTML template? In the template, you would like to use a syntax similar to:

{{ .Label() }}

Solution:

To call a method from a Go template, simply omit the parentheses:

{{ .Label }}

The following Go code demonstrates this:

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

Output:

This is Bob

The documentation specifies that you can call any method that returns one value or two values, provided the second value is of type error. In the latter case, the error is returned if it is non-nil, and template execution is halted.

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