How to use remark-variables #582
-
I can't find how to pass data to the remark-variables plugin Example: How do I pass the name to the plugin? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 2 replies
-
See the readme of |
Beta Was this translation helpful? Give feedback.
-
I know this is 4 years later, but just for anyone else looking for a simple variables approach, here's how I did it with remark-directive plugin: const variablesPlugin = (options: { data: any }) => {
return (tree: Root) => {
visit(tree, (node) => {
if (
node.type === 'textDirective'
) {
const n = node as TextDirective;
if(n.name === 'variable') {
if (n.children.length !== 1 && n.children[0].type !== 'text') {
throw new Error('No text content node found for variable selector');
}
const selectorNode = n.children[0];
if (selectorNode.type !== 'text') {
throw new Error('Only text content is supported for variable selectors');
}
const selector = selectorNode.value.trim();
const value = selector.split('.').reduce((acc, key) => acc && acc[key], options.data);
Object.assign(n, {
type: 'text',
value,
});
}
}
})
}
} Initialize like this: const variables = {
project: {
version: 1
}
};
const processedFile = await unified()
.use(remarkParse)
.use(remarkGfm)
.use(remarkDirective)
.use(variablesPlugin, { data: variables })
.use(remarkRehype)
.use(rehypeStringify)
.process(markdown); And use it in markdown: # Using Variables
This project is currently at version :variable[project.version] |
Beta Was this translation helpful? Give feedback.
See the readme of
react-markdown
: https://github.com/remarkjs/react-markdown#use-a-plugin-with-options