51 lines
1.2 KiB
Go
51 lines
1.2 KiB
Go
package markdown
|
|
|
|
import "fmt"
|
|
import "bytes"
|
|
import "strings"
|
|
import "html/template"
|
|
import "github.com/yuin/goldmark"
|
|
import "github.com/yuin/goldmark/parser"
|
|
import "git.tebibyte.media/sashakoshka/step"
|
|
|
|
var _ step.FuncProvider = new(Provider)
|
|
|
|
// Provider provides Markdown functions.
|
|
type Provider struct {
|
|
// Options contains parse options that are passed to the converter.
|
|
Options []parser.ParseOption
|
|
}
|
|
|
|
// FuncMap fulfills the step.FuncProvider interface.
|
|
func (this *Provider) FuncMap () template.FuncMap {
|
|
stat := &state {
|
|
options: this.Options,
|
|
}
|
|
return template.FuncMap {
|
|
"markdown": stat.funcMarkdown,
|
|
}
|
|
}
|
|
|
|
type state struct {
|
|
options []parser.ParseOption
|
|
}
|
|
|
|
func (this *state) funcMarkdown (input any) (template.HTML, error) {
|
|
builder := strings.Builder { }
|
|
err := goldmark.Convert(toBytes(input), &builder, this.options...)
|
|
if err != nil { return "", nil }
|
|
return template.HTML(builder.String()), nil
|
|
}
|
|
|
|
func toBytes (data any) []byte {
|
|
switch data := data.(type) {
|
|
case []byte: return data
|
|
case string: return []byte(data)
|
|
case template.HTML: return []byte(data)
|
|
default:
|
|
buffer := bytes.Buffer { }
|
|
fmt.Fprint(&buffer, data)
|
|
return buffer.Bytes()
|
|
}
|
|
}
|