htmgo/framework/h/render.go

42 lines
731 B
Go
Raw Permalink Normal View History

2024-01-22 15:22:16 +00:00
package h
import (
"strings"
2024-01-22 15:22:16 +00:00
)
2024-09-21 16:52:56 +00:00
type Ren interface {
2024-09-22 15:46:38 +00:00
Render(context *RenderContext)
2024-09-21 16:52:56 +00:00
}
2024-10-23 14:28:19 +00:00
type RenderOptions struct {
doctype bool
}
type RenderOpt func(context *RenderContext, opt *RenderOptions)
func WithDocType() RenderOpt {
return func(context *RenderContext, opt *RenderOptions) {
opt.doctype = true
}
}
2024-10-26 02:59:17 +00:00
// Render renders the given node recursively, and returns the resulting string.
2024-10-23 14:28:19 +00:00
func Render(node Ren, opts ...RenderOpt) string {
builder := &strings.Builder{}
2024-09-22 15:46:38 +00:00
context := &RenderContext{
builder: builder,
}
2024-10-23 14:28:19 +00:00
options := &RenderOptions{}
for _, opt := range opts {
opt(context, options)
}
if options.doctype {
builder.WriteString("<!DOCTYPE html>")
}
2024-09-22 15:46:38 +00:00
node.Render(context)
return builder.String()
2024-01-22 15:22:16 +00:00
}