132 lines
2.1 KiB
Go
132 lines
2.1 KiB
Go
|
package template_nest
|
||
|
|
||
|
|
||
|
import (
|
||
|
"encoding/json"
|
||
|
"log"
|
||
|
"regexp"
|
||
|
)
|
||
|
|
||
|
|
||
|
type Nest struct {
|
||
|
|
||
|
templateLabel string
|
||
|
templateDir string
|
||
|
templates map[string]string
|
||
|
tokenDelims [2]string
|
||
|
|
||
|
}
|
||
|
|
||
|
|
||
|
func New( templates map[string]string ) Nest {
|
||
|
|
||
|
nest := Nest{
|
||
|
templateLabel: "TEMPLATE",
|
||
|
tokenDelims: [2]string{"<!--%", "%-->"},
|
||
|
templates: templates,
|
||
|
}
|
||
|
|
||
|
return nest
|
||
|
}
|
||
|
|
||
|
|
||
|
|
||
|
|
||
|
func (obj *Nest) Render ( sjson []byte ) string {
|
||
|
|
||
|
var nesti interface{}
|
||
|
err := json.Unmarshal(sjson, &nesti)
|
||
|
if err != nil {
|
||
|
log.Fatal("Failed to parse JSON")
|
||
|
}
|
||
|
|
||
|
nested := nesti.(map[string]interface{})
|
||
|
|
||
|
html := obj._Render( nested )
|
||
|
|
||
|
return html
|
||
|
|
||
|
}
|
||
|
|
||
|
|
||
|
func (obj *Nest) _Render( nested interface{} ) string{
|
||
|
|
||
|
var html string
|
||
|
|
||
|
switch vtype := nested.(type) {
|
||
|
|
||
|
case string:
|
||
|
html = vtype
|
||
|
|
||
|
case []interface{}:
|
||
|
|
||
|
html = obj._RenderArray( vtype )
|
||
|
|
||
|
case map[string]interface{}:
|
||
|
html = obj._RenderMap( vtype )
|
||
|
|
||
|
}
|
||
|
|
||
|
return html
|
||
|
|
||
|
}
|
||
|
|
||
|
|
||
|
func (obj *Nest) _RenderArray( nested []interface{} ) string {
|
||
|
|
||
|
html := ""
|
||
|
for v := range nested {
|
||
|
html += obj._Render( v )
|
||
|
}
|
||
|
|
||
|
return html
|
||
|
}
|
||
|
|
||
|
|
||
|
|
||
|
|
||
|
func (obj *Nest) _RenderMap( nested map[string]interface{} ) string {
|
||
|
|
||
|
templateName := nested[ obj.templateLabel ].(string)
|
||
|
if templateName == "" {
|
||
|
panic("Encountered map with no TEMPLATE label")
|
||
|
}
|
||
|
|
||
|
template := obj.templates[ templateName ]
|
||
|
|
||
|
params := make(map[string]string)
|
||
|
|
||
|
for k, v := range nested {
|
||
|
|
||
|
if k == obj.templateLabel {
|
||
|
continue
|
||
|
}
|
||
|
|
||
|
params[ k ] = obj._Render( v )
|
||
|
|
||
|
}
|
||
|
|
||
|
html := obj._FillIn( templateName, template, params )
|
||
|
|
||
|
return html
|
||
|
|
||
|
}
|
||
|
|
||
|
|
||
|
func (obj *Nest) _FillIn( templateName string, template string, params map[string]string ) string {
|
||
|
|
||
|
html := template
|
||
|
for param, val := range params {
|
||
|
|
||
|
regex, err := regexp.Compile( obj.tokenDelims[0] + `\s*` + param + `\s*` + obj.tokenDelims[1] )
|
||
|
if err != nil {
|
||
|
panic( err )
|
||
|
}
|
||
|
|
||
|
html = regex.ReplaceAllString( html, val )
|
||
|
|
||
|
}
|
||
|
|
||
|
return html
|
||
|
}
|