Template parsing

This commit is contained in:
Eduard Urbach 2016-10-22 14:34:33 +09:00
parent fb4dba31bc
commit d8f76c01d0
2 changed files with 42 additions and 4 deletions

38
main.go
View File

@ -1,21 +1,35 @@
package main
import (
"fmt"
"io"
"reflect"
"strconv"
"strings"
"github.com/Joker/jade"
"github.com/aerojs/aero"
"github.com/animenotifier/arn"
"github.com/buaazp/fasthttprouter"
"github.com/valyala/fasthttp"
"github.com/valyala/fasttemplate"
)
func main() {
arn.Init()
app := aero.New()
jade.PrettyOutput = false
code, _ := jade.ParseFile("pages/anime/anime.pug")
code = strings.TrimSpace(code)
code = strings.Replace(code, "{{ ", "{{", -1)
code = strings.Replace(code, " }}", "}}", -1)
fmt.Println(code)
t := fasttemplate.New(code, "{{", "}}")
app.Get("/", func(ctx *fasthttp.RequestCtx, _ fasthttprouter.Params) {
ctx.Write(ctx.RequestURI())
ctx.Response.Header.Set("content-type", "text/html;charset=utf-8")
ctx.SetBodyString("Hello World")
})
app.Get("/anime/:id", func(ctx *fasthttp.RequestCtx, params fasthttprouter.Params) {
@ -27,8 +41,28 @@ func main() {
return
}
ctx.WriteString(anime.Description)
ctx.Response.Header.Set("content-type", "text/html;charset=utf-8")
writer := ctx.Response.BodyWriter()
t.ExecuteFunc(writer, func(w io.Writer, tag string) (int, error) {
val := reflect.ValueOf(*anime)
parts := strings.Split(tag, ".")
for _, part := range parts {
val = val.FieldByName(part)
}
switch val.Kind() {
case reflect.Int:
num := strconv.FormatInt(val.Int(), 10)
return w.Write([]byte(num))
default:
return w.Write([]byte(val.String()))
}
})
})
fmt.Println("Starting server on http://localhost:5000/")
app.Run()
}

View File

@ -1,2 +1,6 @@
h1 {{.Title.Romaji}}
p {{.Description}}
h1 {{ Title.Romaji }}
p {{ Description }}
if ID
p {{ ID }}
else
p Undefined.