From 0b01489f7d3de9c232056fc9fa1ae8ed67b4a130 Mon Sep 17 00:00:00 2001 From: Matthew Holt Date: Wed, 29 Jul 2015 17:40:11 -0600 Subject: [PATCH] templates: Date -> Now, add Replace and Truncate --- middleware/context.go | 21 ++++++++++++++++++--- 1 file changed, 18 insertions(+), 3 deletions(-) diff --git a/middleware/context.go b/middleware/context.go index 508ec6042..0cd7696ce 100644 --- a/middleware/context.go +++ b/middleware/context.go @@ -6,6 +6,7 @@ import ( "net" "net/http" "net/url" + "strings" "text/template" "time" ) @@ -13,7 +14,7 @@ import ( // This file contains the context and functions available for // use in the templates. -// context is the context with which templates are executed. +// Context is the context with which Caddy templates are executed. type Context struct { Root http.FileSystem Req *http.Request @@ -48,8 +49,8 @@ func (c Context) Include(filename string) (string, error) { return buf.String(), nil } -// Date returns the current timestamp in the specified format -func (c Context) Date(format string) string { +// Now returns the current timestamp in the specified format. +func (c Context) Now(format string) string { return time.Now().Format(format) } @@ -114,3 +115,17 @@ func (c Context) Method() string { func (c Context) PathMatches(pattern string) bool { return Path(c.Req.URL.Path).Matches(pattern) } + +// Truncate truncates the input string to the given length. If +// input is shorter than length, the entire string is returned. +func (c Context) Truncate(input string, length int) string { + if len(input) > length { + return input[:length] + } + return input +} + +// Replace replaces instances of find in input with replacement. +func (c Context) Replace(input, find, replacement string) string { + return strings.Replace(input, find, replacement, -1) +}