[Golang] Create Template Using fmt.Sprintf
In Go, there are text/template and html/template packgaes for templating. But for short pieces of templates, I think fmt.Sprintf is easier to use.
For example, I want to create reStructuredText image code template according to image url. We can use fmt.Sprintf as follows:
package main
import (
"fmt"
)
func rstImage(url, alt string) string {
rst := ""
rst += fmt.Sprintf(".. image:: %s\n", url)
rst += fmt.Sprintf(" :alt: %s\n", alt)
return rst
}
func main() {
rstimg := rstImage("https://golang.org/doc/gopher/pencil/gopherswrench.jpg", "gopherswrench")
fmt.Println(rstimg)
}
As you can see, the code is still easy to read and modify, without the need to define struct for the standard templating packages.
References:
[1] | fmt - The Go Programming Language |