How to use JS expressions in code blocks? #2142
-
I need to use some environment variables in my MDX file. # Heading
{meta.env.CDN_PATH} // here works
```html
<script src="{meta.env.CDN_PATH}" /> // here not works
....... |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
One reason I can think of this isn’t supported, is because MDX doesn’t know your intent is to interpolate. For example what if your intention is to show how your HTML templating library could interpolate data? Another reason is code blocks may contain any kind of language. We’ve all seen HTML templating languages before, but what about this example? ```js
if (condition) { sayHello() }
``` Should it render as this? <pre><code class="language-js">if (condition) { sayHello() }</code></pre> or as this? <pre><code class="language-js">if (condition) {hello}</code></pre> I do see how your use case is useful though. I suggest using // Use any templating library you like here.
import { template } from 'lodash-es'
function InterpolateCodeBlock({ children, ...props }) {
return (
<code {...props}>
{template(children)(props)}
</code>
)
} # Heading
{meta.env.CDN_PATH} // here works
```html meta={meta}
<script src="<%= meta.env.CDN_PATH %>" /> // This is processed using lodash template
``` Then render your document by passing the <MyDocument components={{ code: InterpolateCodeBlock }} /> |
Beta Was this translation helpful? Give feedback.
-
It’s intentional that you can’t break out of code from within code. |
Beta Was this translation helpful? Give feedback.
One reason I can think of this isn’t supported, is because MDX doesn’t know your intent is to interpolate. For example what if your intention is to show how your HTML templating library could interpolate data?
Another reason is code blocks may contain any kind of language. We’ve all seen HTML templating languages before, but what about this example?
Should it render as this?
or as this?
I do see how your use case is useful though. I suggest using
remark-mdx-code-meta
and a custom component.// Use any templatin…