File: renderers.go

package info (click to toggle)
golang-github-johanneskaufmann-html-to-markdown 2.3.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,080 kB
  • sloc: makefile: 3
file content (62 lines) | stat: -rw-r--r-- 1,740 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package base

import (
	"github.com/JohannesKaufmann/dom"
	"github.com/JohannesKaufmann/html-to-markdown/v2/converter"
	"golang.org/x/net/html"
)

// RenderAsHTML will render the node as HTML using `html.Render()`
// Newlines will be inserted depending on the configured `TagType`.
//
// As an example, you could do such a combination:
//
//	"A text with <strong>bold</strong> and *italic* text"`
func RenderAsHTML(ctx converter.Context, w converter.Writer, node *html.Node) converter.RenderStatus {
	tagName := dom.NodeName(node)
	tagType, _ := ctx.GetTagType(tagName)

	if tagType == converter.TagTypeBlock {
		w.WriteString("\n\n")
	}
	_ = html.Render(w, node) // TODO: what to do with error?
	if tagType == converter.TagTypeBlock {
		w.WriteString("\n\n")
	}

	return converter.RenderSuccess
}

// RenderAsHTMLWrapper will render the node as HTML
// and render the children as markdown.
func RenderAsHTMLWrapper(ctx converter.Context, w converter.Writer, node *html.Node) converter.RenderStatus {
	name := dom.NodeName(node)

	w.WriteString("<")
	w.WriteString(name)
	// TODO: also render the attributes?
	w.WriteString(">\n\n")

	ctx.RenderChildNodes(ctx, w, node)

	w.WriteString("\n\n</")
	w.WriteString(name)
	w.WriteString(">")
	return converter.RenderSuccess
}

// RenderAsPlaintextWrapper will keep the children of this node as markdown.
func RenderAsPlaintextWrapper(ctx converter.Context, w converter.Writer, node *html.Node) converter.RenderStatus {
	tagName := dom.NodeName(node)
	tagType, _ := ctx.GetTagType(tagName)

	if tagType == converter.TagTypeBlock {
		w.WriteString("\n\n")
	}
	ctx.RenderChildNodes(ctx, w, node)
	if tagType == converter.TagTypeBlock {
		w.WriteString("\n\n")
	}

	return converter.RenderSuccess
}