render method - first version

This commit is contained in:
Tom Gracey 2024-11-13 22:56:24 +00:00
commit 0152ebeb91
2 changed files with 173 additions and 0 deletions

131
template_nest/nest.go Normal file

@ -0,0 +1,131 @@
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
}

42
test_nest.go Normal file

@ -0,0 +1,42 @@
package main
import (
"fmt"
"tntester/template_nest"
)
func main(){
templates := map[string]string{
"00-simple-page": `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Simple Page</title>
</head>
<body>
<p>A fairly simple page to test the performance of Template::Nest.</p>
<p><!--% variable %--></p>
<!--% simple_component %-->
</body>
</html>`, "00-simple-component": `<p><!--% variable %--></p>`}
json := []byte(`{
"TEMPLATE": "00-simple-page",
"variable": "Simple Variable",
"simple_component": {
"TEMPLATE":"01-simple-component",
"variable": "Simple Variable in Simple Component"
}
}`)
nest := template_nest.New( templates )
html := nest.Render( json )
fmt.Println( html )
}