Skip to content

Instantly share code, notes, and snippets.

@MatthewVita
Last active August 29, 2015 14:07
Show Gist options
  • Save MatthewVita/62ce4b2f33762d94026a to your computer and use it in GitHub Desktop.
Save MatthewVita/62ce4b2f33762d94026a to your computer and use it in GitHub Desktop.
AmberParser.go - Convenience package for parsing Amber templates with JSON parameters
/*
*@desc: Convenience package for parsing
* Amber templates with JSON parameters
*
*@use:
ambrPrsr := amberParser.New("src/views/foobar.amber", `{
"favorite_color":"grey",
"year":"2014",
"baz":"bar"
}`)
ambrRes, ambrErr := ambrPrsr.Parse()
*/
package amberParser
import (
"bytes"
"encoding/json"
"github.com/eknkc/amber"
)
type AmberParser struct {
file string
options string
}
func New(file string, options string) *AmberParser {
return &AmberParser{file, options}
}
func (this *AmberParser) Parse() (string, error) {
ambr := amber.New()
abmrParseErr := ambr.ParseFile(this.file)
var res string
if abmrParseErr != nil {
return "", abmrParseErr
}
tpl, ambrCompileErr := ambr.Compile()
if ambrCompileErr == nil {
var outTpl bytes.Buffer
jsonRes := map[string]interface{}{}
ambrJsonErr := json.Unmarshal([]byte(this.options), &jsonRes)
if ambrJsonErr != nil {
return "", ambrJsonErr
}
tpl.Execute(&outTpl, jsonRes)
res = outTpl.String()
}
return res, nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment