mdx-js / mdx

Markdown for the component era
https://mdxjs.com
MIT License
17.76k stars 1.14k forks source link

Allow javascript expression in markdown links [](myvar.foo}) #2411

Closed fhacloid closed 11 months ago

fhacloid commented 11 months ago

Initial checklist

Problem

Hi there,

I was trying to use variables to manage links inside my documentation. My objective is to use variables for almost all of my links inside my docs to centralise links management.

I had declared an object that contains all my links like that:

export const Links = {
  "foo": "bar",
  "bar": "https://external.goo.com"
}

And I try to use those variables as link uri in a markdown link tag [Description]({Links.foo})

The issue is that MDX seems to not interpret the variable inside the () so the rendered content has this result :

export const Links = {
  "foo": "bar",
  "bar": "https://external.goo.com"
}

[the url should be "bar", but is literal {Links.foo}]({Links.foo})

Rendering:

[the url should be "bar", but is literal {Links.foo}]({Links.foo})

Should be:

[the url should be "bar", but is literal {Links.foo}](bar)

Solution

I don't have much knowledge about js or mdx, but my guess would be to parse and interpret brackets expressions inside the link () part of a []() markdown link.

This example below should work:

const url = "https://facebook.com"

Please ! Check my cool [website]({url})

Rendered as:

Please ! Check my cool [website](https://facebook.com)

Alternatives

I saw the documentation about components used for rendering, maybe there is an escape hatch that I could use to override the component that manage links ?

(I am not a react developer, so I don't know about either the possibility or how to do it.)

Feel free to correct me or pointing me to a solution I could implement. Thank you for your time in advance. :)

wooorm commented 11 months ago

Hi!

MDX is not a templating language where you can add variables anywhere you want. So you can’t put braces anywhere (and that’s not a goal).

Markdown already has references/definitions. You don’t need variables to solve this:

Some [link][some-url]

[some-url]: https://whatever

You can also already use JSX for this:

export const whatever = 'https://example'

Like <a href={whatever}>*this*</a>.
fhacloid commented 11 months ago

Thank you very much, didn't knew that reference existed in markdown :)