Replies: 3 comments 21 replies
-
Your heading thing seems to work for me, too. Interestingly, I get an error when trying to do the dynamic import based on the slug. I did a similar example test with the following: <script context="module">
export async function load(context) {
const Post = await import("$lib/components/header.svelte");
console.log(Post);
const Post2 = await import("$lib/posts/foo.md");
console.log(Post);
const test = "$lib/posts/" + context.page.params.slug + ".md";
console.log(test);
const Post3 = await import(test);
return {
props: {
slug: context.page.params.slug
},
};
}
</script> The first two work fine, and the third one causes an error: |
Beta Was this translation helpful? Give feedback.
-
You could pull out the headings with a remark plugin, something like this would work: function get_headings() {
let visit;
let tree_to_string;
return async function transformer(tree, vFile) {
if (!visit) {
tree_to_string = (await import('mdast-util-to-string')).toString;
visit = (await import('unist-util-visit')).visit;
}
vFile.data.headings = [];
visit(tree, 'heading', (node) => {
vFile.data.headings.push({
level: node.depth,
title: tree_to_string(node),
});
});
if (!vFile.data.fm) vFile.data.fm = {};
vFile.data.fm.headings = vFile.data.headings;
};
}
// later
mdsvex({ remarkPlugins: [ get_headings() ] }) Then an array of headings would be available on the metadata object and you could use those for whatever you wanted. |
Beta Was this translation helpful? Give feedback.
-
@pngwn I am trying to use your example to generate TOC, it works just fine, thank you. But I need to use it as rehype, not remark. Using the code below I get the TOC data I need, but it do not appear in metadata object somehow... import { visit } from "unist-util-visit";
const checkHeading = node => {
let name = "";
let level = 0;
if (node && node.type === "element") {
name = node.tagName.toLowerCase() || "";
}
if (name.length === 2 && name[0] === "h") {
level = name[1];
}
return (level < 7)
? level
: 0;
};
export const transformerTOC = () => (tree, vFile) => {
const toc = [];
visit(tree, "element", node => {
const heading = checkHeading(node);
if (heading) {
toc.push({
id: node.properties.id,
level: heading,
title: node.children[0].value
});
}
});
if (!vFile.data.fm) {
vFile.data.fm = {};
}
vFile.data.fm.toc = toc;
}; What am I doing wrong? |
Beta Was this translation helpful? Give feedback.
-
Hi, does anyone have any experience with getting headings out of markdown files?
I'm using MDsveX with SvelteKit and I can get the metadata fine but I'm trying to access headings as well from the actual file, here's what I'm using in the index of the project:
Then in the
[slug].svelte
this:Ideally I'd want to have access to the headings for the index page and to use as a ToC in the
[slug].svelte
component.Any pointers appreciated, thanks
Beta Was this translation helpful? Give feedback.
All reactions