mirror of https://github.com/mickael-menu/zk
Add the {{prepend}} template helper to quote or indent a paragraph
parent
9a397eff61
commit
31c13c6af4
@ -0,0 +1,33 @@
|
|||||||
|
package helpers
|
||||||
|
|
||||||
|
import (
|
||||||
|
"github.com/aymerick/raymond"
|
||||||
|
"github.com/mickael-menu/zk/util"
|
||||||
|
"github.com/mickael-menu/zk/util/strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
// RegisterPrepend registers a {{prepend}} template helper which prepend a
|
||||||
|
// given string at the beginning of each line.
|
||||||
|
//
|
||||||
|
// {{prepend '> ' 'A quote'}} -> "> A quote"
|
||||||
|
// {{#prepend '> '}}A quote{{/prepend}} -> "> A quote"
|
||||||
|
//
|
||||||
|
// A quote on
|
||||||
|
// several lines
|
||||||
|
// {{/prepend}}
|
||||||
|
//
|
||||||
|
// > A quote on
|
||||||
|
// > several lines
|
||||||
|
func RegisterPrepend(logger util.Logger) {
|
||||||
|
raymond.RegisterHelper("prepend", func(prefix string, opt interface{}) string {
|
||||||
|
switch arg := opt.(type) {
|
||||||
|
case *raymond.Options:
|
||||||
|
return strings.Prepend(arg.Fn(), prefix)
|
||||||
|
case string:
|
||||||
|
return strings.Prepend(arg, prefix)
|
||||||
|
default:
|
||||||
|
logger.Printf("the {{prepend}} template helper is expecting a string as argument, received: %v", opt)
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
@ -0,0 +1,18 @@
|
|||||||
|
package strings
|
||||||
|
|
||||||
|
import "strings"
|
||||||
|
|
||||||
|
// Prepend prefixes each lines of a string with the given prefix.
|
||||||
|
// It can be used to indent or quote (> ) a paragraph, for example.
|
||||||
|
func Prepend(text string, prefix string) string {
|
||||||
|
if text == "" || prefix == "" {
|
||||||
|
return text
|
||||||
|
}
|
||||||
|
|
||||||
|
lines := strings.SplitAfter(text, "\n")
|
||||||
|
if len(lines[len(lines)-1]) == 0 {
|
||||||
|
lines = lines[:len(lines)-1]
|
||||||
|
}
|
||||||
|
|
||||||
|
return strings.Join(append([]string{""}, lines...), prefix)
|
||||||
|
}
|
@ -0,0 +1,19 @@
|
|||||||
|
package strings
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/mickael-menu/zk/util/assert"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestPrepend(t *testing.T) {
|
||||||
|
test := func(text string, prefix string, expected string) {
|
||||||
|
assert.Equal(t, Prepend(text, prefix), expected)
|
||||||
|
}
|
||||||
|
|
||||||
|
test("", "> ", "")
|
||||||
|
test("One line", "> ", "> One line")
|
||||||
|
test("One line\nTwo lines", "> ", "> One line\n> Two lines")
|
||||||
|
test("One line\nTwo lines\nThree lines", "> ", "> One line\n> Two lines\n> Three lines")
|
||||||
|
test("Newline\n", "> ", "> Newline\n")
|
||||||
|
}
|
Loading…
Reference in New Issue