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

How to Call Go Methods from Within HTML Templates?

Barbara Streisand
Release: 2024-12-25 05:59:12
Original
706 people have browsed it

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

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

{{ .Label() }}
Copy after login

Solution:

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

{{ .Label }}
Copy after login

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

Output:

This is Bob
Copy after login

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!

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