Extracting headings from content #493
-
Hello. I'm trying to set up an open source blog using sveltekit & markdoc. Every blog post will have an automatically generated table of contents for the article, however I reached two walls which I'm unable to get past
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Here's an example that shows how to parse the document, iterate over the AST, identify the headings, and extract the heading text, level, and ID: import Markdoc from "@markdoc/markdoc";
const example = `
# This is a test {% #test-1 %}
## This is another test
### One more test {% #test-3 %}
`;
const ast = Markdoc.parse(example);
function getNodeText(node) {
let content = '';
for (const {type, attributes} of node.walk())
if (type === 'text' && typeof attributes.content === 'string')
content += attributes.content;
return content;
}
function* getTOC(ast) {
for (const node of ast.walk())
if (node.type === 'heading')
yield {content: getNodeText(node), attributes: node.attributes};
}
for (const {content, attributes: {level, id}} of getTOC(ast))
console.log(content, level, id); You can build a table of contents that links to each ID in order to jump directly to the location in the page. Also, there's a useful example in the Markdoc documentation that demonstrates how to programmatically assign an ID to each heading automatically if you don't want to have to declare them yourself. You could use the |
Beta Was this translation helpful? Give feedback.
Here's an example that shows how to parse the document, iterate over the AST, identify the headings, and extract the heading text, level, and ID: