mirror of
https://github.com/caddyserver/caddy.git
synced 2024-11-24 09:15:14 +08:00
More template functions
This commit is contained in:
parent
3ec870cb56
commit
55801b48ec
|
@ -3,6 +3,7 @@ package templates
|
||||||
import (
|
import (
|
||||||
"io/ioutil"
|
"io/ioutil"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
// This file contains the context and functions available for
|
// This file contains the context and functions available for
|
||||||
|
@ -11,6 +12,7 @@ import (
|
||||||
// context is the context with which templates are executed.
|
// context is the context with which templates are executed.
|
||||||
type context struct {
|
type context struct {
|
||||||
root http.FileSystem
|
root http.FileSystem
|
||||||
|
req *http.Request
|
||||||
}
|
}
|
||||||
|
|
||||||
// Include returns the contents of filename relative to the site root
|
// Include returns the contents of filename relative to the site root
|
||||||
|
@ -22,3 +24,29 @@ func (c context) Include(filename string) (string, error) {
|
||||||
body, err := ioutil.ReadAll(file)
|
body, err := ioutil.ReadAll(file)
|
||||||
return string(body), err
|
return string(body), err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Date returns the current timestamp in the specified format
|
||||||
|
func (c context) Date(format string) string {
|
||||||
|
return time.Now().Format(format)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Cookie gets the value of a cookie with name name.
|
||||||
|
func (c context) Cookie(name string) string {
|
||||||
|
cookies := c.req.Cookies()
|
||||||
|
for _, cookie := range cookies {
|
||||||
|
if cookie.Name == name {
|
||||||
|
return cookie.Value
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
// Header gets the value of a request header with field name.
|
||||||
|
func (c context) Header(name string) string {
|
||||||
|
return c.req.Header.Get(name)
|
||||||
|
}
|
||||||
|
|
||||||
|
// RemoteAddr gets the address of the client making the request.
|
||||||
|
func (c context) RemoteAddr() string {
|
||||||
|
return c.req.RemoteAddr
|
||||||
|
}
|
||||||
|
|
|
@ -38,7 +38,7 @@ func (t Templates) ServeHTTP(w http.ResponseWriter, r *http.Request) (int, error
|
||||||
for _, ext := range rule.Extensions {
|
for _, ext := range rule.Extensions {
|
||||||
if reqExt == ext {
|
if reqExt == ext {
|
||||||
// Create execution context
|
// Create execution context
|
||||||
ctx := context{root: http.Dir(t.Root)}
|
ctx := context{root: http.Dir(t.Root), req: r}
|
||||||
|
|
||||||
// Build the template
|
// Build the template
|
||||||
tpl, err := template.ParseFiles(t.Root + r.URL.Path)
|
tpl, err := template.ParseFiles(t.Root + r.URL.Path)
|
||||||
|
|
Loading…
Reference in New Issue
Block a user