Golang – Template

In python I can use Jinja2 template module to parse variables to Cisco command template, in Golang there is text/template which is similar to Jinja2 template engine for python.

This recipe gives an example on how to parse variables into a text template. The types within the struct have to be exported in order for template to parse the text template otherwise error will be thrown by golang which looks like this:

Error due to unexportable type in struct.
package main

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

type configureVlan struct {
	// Struct has to have Exported types, so the first character has to be capitalized in order
	// for template to parse.
	Vlan uint
	Name string
}

func main() {
	vlanCmd := `
conf t
vlan {{ .Vlan }}
name {{ .Name }}
end
	`
	v := configureVlan{
		100,
		"vlan100",
	}
	tmpl, e := template.New("vlan").Parse(vlanCmd)
	if e != nil {
		log.Fatal(e)
	}

	err := tmpl.Execute(os.Stdout, v)
	if err != nil {
		log.Fatal(err)
	}
}

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s