Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: support nested templates #49

Merged
merged 5 commits into from
Mar 12, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions context.go
Original file line number Diff line number Diff line change
Expand Up @@ -142,13 +142,13 @@ func (p *Context) JSON(code int, data interface{}) {

func (p *Context) YAP(code int, yapFile string, data interface{}) {
w := p.ResponseWriter
t, err := p.engine.templ(yapFile)
if err != nil {
log.Panicf("YAP `%s`: %v\n", yapFile, err)
t := p.engine.templ(yapFile)
if t == nil {
log.Panicln("YAP: not find template:", yapFile)
}
h := w.Header()
h.Set("Content-Type", "text/html")
err = t.Execute(w, data)
err := t.Execute(w, data)
if err != nil {
log.Panicln("YAP:", err)
}
Expand Down
21 changes: 21 additions & 0 deletions demo/blog_nestetemplate/blog.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package main

import (
"os"

"github.com/goplus/yap"
)

func main() {
y := yap.New(os.DirFS("."))

y.GET("/", func(ctx *yap.Context) {
ctx.TEXT(200, "text/html", `<html><body>Hello, <a href="/p/123">YAP</a>!</body></html>`)
})
y.GET("/p/:id", func(ctx *yap.Context) {
ctx.YAP(200, "blog", yap.H{
"Id": ctx.Param("id"),
})
})
y.Run(":8888")
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[golangci-lint] Error return value of y.Run is not checked (errcheck)

If you have any questions about this comment, feel free to raise an issue here:

}
13 changes: 13 additions & 0 deletions demo/blog_nestetemplate/yap/blog_yap.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>neste-template</title>
</head>
<body>
{{ template "header" }}
<h1>neste-template</h1>
<h3>{{ .Id }}</h3>
</body>
</html>
3 changes: 3 additions & 0 deletions demo/blog_nestetemplate/yap/layout_yap.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{{ define "header"}}
<h1>header</h1>
{{ end}}
10 changes: 10 additions & 0 deletions demo/classfile_nestetemplate/blog_yap.gox
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
get "/", ctx => {
ctx.html `<html><body>Hello, <a href="/p/123">YAP</a>!</body></html>`
}
get "/p/:id", ctx => {
ctx.yap "blog", {
"Id": ctx.param("id"),
}
}

run ":8888"
29 changes: 29 additions & 0 deletions demo/classfile_nestetemplate/gop_autogen.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

13 changes: 13 additions & 0 deletions demo/classfile_nestetemplate/yap/blog_yap.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>neste-template</title>
</head>
<body>
{{ template "header" }}
<h1>neste-template</h1>
<h3>{{ .Id }}</h3>
</body>
</html>
3 changes: 3 additions & 0 deletions demo/classfile_nestetemplate/yap/layout_yap.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{{ define "header"}}
<h1>header</h1>
{{ end}}
117 changes: 115 additions & 2 deletions template.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,13 @@
package yap

import (
"fmt"
"html/template"
"io/fs"
"log"
"os"
"path/filepath"
"strings"

"github.com/goplus/yap/internal/templ"
)
Expand All @@ -32,8 +36,11 @@ type Template struct {
}

// NewTemplate allocates a new, undefined template with the given name.
func NewTemplate(name string) Template {
return Template{template.New(name)}
func NewTemplate(name string) *Template {
return &Template{template.New(name)}
}
func (t *Template) NewTemplate(name string) *Template {
return &Template{Template: t.Template.New(name)}
}

func (t Template) Parse(text string) (ret Template, err error) {
Expand All @@ -49,3 +56,109 @@ func ParseFSFile(f fs.FS, file string) (t Template, err error) {
name := filepath.Base(file)
return NewTemplate(name).Parse(string(b))
}

func ParseFiles(filenames ...string) (*Template, error) {
return parseFiles(nil, readFileOS, filenames...)
}

func (t *Template) ParseFiles(filenames ...string) (*Template, error) {
return parseFiles(t, readFileOS, filenames...)
}

func parseFiles(t *Template, readFile func(string) (string, []byte, error), filenames ...string) (*Template, error) {

if len(filenames) == 0 {
return nil, fmt.Errorf("yap/template: no files named in call to ParseFiles")
}
for _, filename := range filenames {
name, b, err := readFile(filename)
if err != nil {
return nil, err
}
s := string(b)
var tmpl *Template
if t == nil {
t = NewTemplate(name)
}
if name == t.Name() {
tmpl = t
} else {
tmpl = t.NewTemplate(name)
}
_, err = tmpl.Parse(s)
if err != nil {
return nil, err
}
}
log.Println("yap/template list:")
for i, t2 := range t.Templates() {
log.Println(i, t2.Name())
}
return t, nil
}

func ParseGlob(pattern string) (*Template, error) {
return parseGlob(nil, pattern)
}

func (t *Template) ParseGlob(pattern string) (*Template, error) {
return parseGlob(t, pattern)
}

func parseGlob(t *Template, pattern string) (*Template, error) {
filenames, err := filepath.Glob(pattern)
if err != nil {
return nil, err
}
if len(filenames) == 0 {
return nil, fmt.Errorf("html/template: pattern matches no files: %#q", pattern)
}
return parseFiles(t, readFileOS, filenames...)
}

// ParseFS is like ParseFiles or ParseGlob but reads from the file system fs
// instead of the host operating system's file system.
// It accepts a list of glob patterns.
// (Note that most file names serve as glob patterns matching only themselves.)
func ParseFS(fs fs.FS, patterns ...string) (*Template, error) {
return parseFS(nil, fs, patterns)
}

// ParseFS is like ParseFiles or ParseGlob but reads from the file system fs
// instead of the host operating system's file system.
// It accepts a list of glob patterns.
// (Note that most file names serve as glob patterns matching only themselves.)
func (t *Template) ParseFS(fs fs.FS, patterns ...string) (*Template, error) {
return parseFS(t, fs, patterns)
}

func parseFS(t *Template, fsys fs.FS, patterns []string) (*Template, error) {
var filenames []string
for _, pattern := range patterns {
list, err := fs.Glob(fsys, pattern)
if err != nil {
return nil, err
}
if len(list) == 0 {
return nil, fmt.Errorf("template: pattern matches no files: %#q", pattern)
}
filenames = append(filenames, list...)
}
return parseFiles(t, readFileFS(fsys), filenames...)
}

func readFileOS(file string) (name string, b []byte, err error) {
name = filepath.Base(file)
b, err = os.ReadFile(file)
return
}

func readFileFS(fsys fs.FS) func(string) (string, []byte, error) {
return func(file string) (name string, b []byte, err error) {
name = filepath.ToSlash(file)
// compatible yap template name for older versions of yap, without the suffix "_ yap.html"
name = strings.TrimSuffix(name, "_yap.html")
b, err = fs.ReadFile(fsys, file)
return
}
}
34 changes: 17 additions & 17 deletions yap.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
package yap

import (
"html/template"
"io/fs"
"log"
"net/http"
Expand All @@ -32,9 +33,9 @@ type Engine struct {
router
Mux *http.ServeMux

tpls map[string]Template
fs fs.FS
las func(addr string, handler http.Handler) error
tpl *Template
fs fs.FS
las func(addr string, handler http.Handler) error
}

// New creates a YAP engine.
Expand Down Expand Up @@ -65,7 +66,15 @@ func (p *Engine) initYapFS(fsys fs.FS) {
}
}
p.fs = fsys
p.tpls = make(map[string]Template)
}

// Load template
func (p *Engine) loadTemplate() {
t, err := parseFS(NewTemplate(""), p.yapFS(), []string{"*_yap.html"})
if err != nil {
log.Panicln(err)
}
p.tpl = t
}

func (p *Engine) yapFS() fs.FS {
Expand Down Expand Up @@ -154,20 +163,11 @@ func (p *Engine) SetLAS(listenAndServe func(addr string, handler http.Handler) e
p.las = listenAndServe
}

func (p *Engine) templ(path string) (t Template, err error) {
fsys := p.yapFS()
if p.tpls == nil {
return Template{}, os.ErrNotExist
}
t, ok := p.tpls[path]
if !ok {
t, err = ParseFSFile(fsys, path+"_yap.html")
if err != nil {
return
}
p.tpls[path] = t
func (p *Engine) templ(path string) *template.Template {
if p.tpl == nil {
p.loadTemplate()
}
return
return p.tpl.Lookup(path)
}

// SubFS returns a sub filesystem by specified a dir.
Expand Down