embed.go

v0.1.0
Doc Versions Source
1
package template
2
3
import (
4
	"fmt"
5
	"strings"
6
)
7
8
// Embed inserts content between marker comments in a template.
9
// The markers should be XML comments like <!-- MD_CONTENT_START --> and <!-- MD_CONTENT_END -->.
10
func Embed(templateXML, content, markerStart, markerEnd string) (string, error) {
11
	startIdx := strings.Index(templateXML, markerStart)
12
	if startIdx == -1 {
13
		return "", fmt.Errorf("start marker %q not found in template", markerStart)
14
	}
15
	endIdx := strings.Index(templateXML, markerEnd)
16
	if endIdx == -1 {
17
		return "", fmt.Errorf("end marker %q not found in template", markerEnd)
18
	}
19
	if endIdx < startIdx {
20
		return "", fmt.Errorf("end marker appears before start marker")
21
	}
22
23
	var buf strings.Builder
24
	buf.WriteString(templateXML[:startIdx+len(markerStart)])
25
	buf.WriteString("\n")
26
	buf.WriteString(content)
27
	buf.WriteString("\n")
28
	buf.WriteString(templateXML[endIdx:])
29
30
	return buf.String(), nil
31
}
32

Source Files