caddy/config/setup/templates.go

91 lines
1.8 KiB
Go
Raw Normal View History

2015-05-04 20:49:49 +03:00
package setup
import (
"net/http"
2015-05-04 20:49:49 +03:00
"github.com/mholt/caddy/middleware"
"github.com/mholt/caddy/middleware/templates"
)
// Templates configures a new Templates middleware instance.
func Templates(c *Controller) (middleware.Middleware, error) {
rules, err := templatesParse(c)
if err != nil {
return nil, err
}
tmpls := templates.Templates{
Rules: rules,
Root: c.Root,
FileSys: http.Dir(c.Root),
2015-05-04 20:49:49 +03:00
}
return func(next middleware.Handler) middleware.Handler {
tmpls.Next = next
return tmpls
}, nil
}
func templatesParse(c *Controller) ([]templates.Rule, error) {
var rules []templates.Rule
for c.Next() {
var rule templates.Rule
rule.Path = defaultTemplatePath
rule.Extensions = defaultTemplateExtensions
args := c.RemainingArgs()
switch len(args) {
case 0:
// Optional block
for c.NextBlock() {
switch c.Val() {
case "path":
args := c.RemainingArgs()
if len(args) != 1 {
return nil, c.ArgErr()
}
rule.Path = args[0]
case "ext":
args := c.RemainingArgs()
if len(args) == 0 {
return nil, c.ArgErr()
}
rule.Extensions = args
case "between":
args := c.RemainingArgs()
if len(args) != 2 {
return nil, c.ArgErr()
}
rule.Delims[0] = args[0]
rule.Delims[1] = args[1]
}
}
default:
2015-05-04 20:49:49 +03:00
// First argument would be the path
rule.Path = args[0]
2015-05-04 20:49:49 +03:00
// Any remaining arguments are extensions
rule.Extensions = args[1:]
2015-05-04 20:49:49 +03:00
if len(rule.Extensions) == 0 {
2015-06-27 01:19:44 +03:00
rule.Extensions = defaultTemplateExtensions
2015-05-04 20:49:49 +03:00
}
}
for _, ext := range rule.Extensions {
rule.IndexFiles = append(rule.IndexFiles, "index"+ext)
}
2015-05-04 20:49:49 +03:00
rules = append(rules, rule)
}
return rules, nil
}
2015-06-27 01:19:44 +03:00
const defaultTemplatePath = "/"
2015-05-04 20:49:49 +03:00
2015-06-27 01:19:44 +03:00
var defaultTemplateExtensions = []string{".html", ".htm", ".tmpl", ".tpl", ".txt"}