[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:

Run Code on Go Playground

package main

import (

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

As you can see, the code is still easy to read and modify, without the need to define struct for the standard templating packages.


[1]fmt - The Go Programming Language