Last active
August 29, 2015 14:07
-
-
Save MatthewVita/62ce4b2f33762d94026a to your computer and use it in GitHub Desktop.
AmberParser.go - Convenience package for parsing Amber templates with JSON parameters
This file contains 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
/* | |
*@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