[Golang] Serve Template Data From YAML File


Extract template data from human readable YAML file and create textual/HTML output by Golang text/template or html/template package.

Assume we have the following data stored in YAML file:

tmpldata.yaml | repository | view raw
1
2
3
4
sitename: Theory and Practice
og:
  Url: https://siongui.github.io/
  Locale: en_US

We want to apply the above data to the template of text/template or html/template package to create textual/HTML output.

First use Google [2] to find Go YAML parser. I found github.com/ghodss/yaml [3] is a good choice because we can define a struct once and use it for both JSON and YAML. Install the YAML parser by:

$ go get -u github.com/ghodss/yaml

Then we will read the data from YAML file, parse the YAML data, and store the result in a pre-defined struct, i.e., Unmarshal the YAML data. This is what the following code does:

yml.go | repository | view raw
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
package yamldata

import (
	"github.com/ghodss/yaml"
	"io/ioutil"
)

type TemplateData struct {
	SiteName string            `json:"sitename"`
	Og       map[string]string `json:"og"`
}

func YamlToStruct(path string) (td TemplateData, err error) {
	b, err := ioutil.ReadFile(path)
	if err != nil {
		return
	}

	err = yaml.Unmarshal(b, &td)
	if err != nil {
		return
	}

	return
}

Now the data is stored in the struct, and we apply the data to Go template and create output by following code:

yml_test.go | repository | view raw
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
package yamldata

import (
	"os"
	"testing"
	"text/template"
)

const tmpl = `
sitename: {{.SiteName}}
open graph url: {{.Og.Url}}
open graph locale: {{.Og.Locale}}
`

func TestServeFromYAML(t *testing.T) {
	data, err := YamlToStruct("tmpldata.yaml")
	if err != nil {
		t.Error(err)
	}

	tl, err := template.New("").Parse(tmpl)
	if err != nil {
		t.Error(err)
	}

	err = tl.Execute(os.Stdout, &data)
	if err != nil {
		t.Error(err)
	}
}

The output is ass follows:

=== RUN   TestServeFromYAML

sitename: Theory and Practice
open graph url: https://siongui.github.io/
open graph locale: en_US
--- PASS: TestServeFromYAML (0.00s)
PASS

Tested on:

  • Ubuntu Linux 16.10
  • Go 1.7.5