Replies: 3 comments
-
You can use |
Beta Was this translation helpful? Give feedback.
-
You could do the following with md := goldmark.New()
reader := text.NewReader(markdownContent)
doc := md.Parser().Parse(reader)
// AppendChild removes the node from doc. To be able to use Walk correctly
// we shouldn't modify the original doc in Walk.
var segments [][]ast.Node
ast.Walk(doc, func(n ast.Node, entering bool) (ast.WalkStatus, error) {
if !entering || n.Type() == ast.TypeDocument {
return ast.WalkContinue, nil
}
if _, ok := n.(*ast.Heading); ok {
segments = append(segments, nil)
}
if len(segments) > 0 {
segment := segments[len(segments)-1]
segment = append(segment, n)
segments[len(segments)-1] = segment
}
return ast.WalkSkipChildren, nil
})
var sections []string
for i := range segments {
doc := ast.NewDocument()
for _, node := range segments[i] {
doc.AppendChild(doc, node)
}
var b strings.Builder
if err := md.Renderer().Render(&b, markdownContent, doc); err != nil {
t.Fatal(err)
}
sections = append(sections, b.String())
}
// Do what you need to do
log.Printf("%#v", sections) |
Beta Was this translation helpful? Give feedback.
-
I use hugo.
It's a very common layout, advised by the w3c. Goldmark should make it possible easily. |
Beta Was this translation helpful? Give feedback.
-
I would like to split a markdown document into sections, separated by headlines (preserving the headline in each section). I'd also be interested in rendering a single section only.
A quick and dirty solution would be to render the entire document and then parse the HTML output using golang.org/x/net/html or something similar and split up the output, but I'd prefer to do this using a custom render procedure.
A quick example of what I'd like to achieve:
Input:
Output:
Any hints are welcome!
Beta Was this translation helpful? Give feedback.
All reactions