Last active
June 3, 2016 01:02
-
-
Save josephspurrier/c59f865676aecd4e7b35707f08646465 to your computer and use it in GitHub Desktop.
Fill a template with variables in Go
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"encoding/json" | |
"io/ioutil" | |
"log" | |
"os" | |
"path/filepath" | |
"text/template" | |
) | |
func main() { | |
err := generate("output/test.go", "test") | |
if err != nil { | |
log.Fatal(err) | |
} | |
log.Println("Generated successfully") | |
} | |
func generate(file string, name string) error { | |
// File paths | |
tPath := filepath.Join("template", name+".gen") | |
vPath := filepath.Join("template", name+".json") | |
// Read the config file | |
b, err := ioutil.ReadFile(vPath) | |
if err != nil { | |
return err | |
} | |
// Convert json to interface | |
var d map[string]interface{} | |
err = json.Unmarshal(b, &d) | |
if err != nil { | |
return err | |
} | |
// Parse the template | |
t, err := template.ParseFiles(tPath) | |
if err != nil { | |
return err | |
} | |
// Create the output file | |
f, err := os.Create(file) | |
if err != nil { | |
return err | |
} | |
defer f.Close() | |
// Fills template with variables and writes to file | |
err = t.Execute(f, d) | |
if err != nil { | |
return err | |
} | |
return nil | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Template: | |
{ | |
"table": "note", | |
"chair": [ | |
"walnut", | |
"cherry", | |
"pine", | |
], | |
"desk": { | |
"drawer":"pen" | |
} | |
} | |
Variables: | |
var ( | |
table = "{{.table}}" | |
chair = "{{index .chair 1}}" | |
desk = "{{.desk.drawer}}" | |
) | |
Output: | |
var ( | |
table = "note" | |
chair = "cherry" | |
desk = "pen" | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment