Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Suggestion to improve the docs for the Code component #7078

Open
ttmc opened this issue Feb 28, 2024 · 1 comment
Open

Suggestion to improve the docs for the Code component #7078

ttmc opened this issue Feb 28, 2024 · 1 comment

Comments

@ttmc
Copy link

ttmc commented Feb 28, 2024

The docs about the Code component give examples of how you could use it in an Astro file (.astro):

---
import { Code } from 'astro:components';
---
<!-- Syntax highlight some JavaScript code. -->
<Code code={`const foo = 'bar';`} lang="js" />
<!-- Optional: Customize your theme. -->
<Code code={`const foo = 'bar';`} lang="js" theme="dark-plus" />
<!-- Optional: Enable word wrapping. -->
<Code code={`const foo = 'bar';`} lang="js" wrap />
<!-- Optional: Output inline code. -->
<p>
  <Code code={`const foo = 'bar';`} lang="js" inline />
  will be rendered inline.
</p>

I found that one must be very careful to inspect their code and replace \n with \\n, otherwise it will be converted to an actual newline in the rendered output. Similarly, \t must be replaced with \\t, and so on. Backticks-in-code must also be escaped. Doing that is tricky and error-prone. Ideally, one could just copy some raw code from their IDE/text editor straight into their .astro file, somewhere, and be done.

Good news: it's possible, and here's how... just append String.raw before the first backtick. That way everything inside the backticks will be interepreted as a raw string.

The above example code, in the docs, would become:

---
import { Code } from 'astro:components';
---
<!-- Syntax highlight some JavaScript code. -->
<Code code={String.raw`const foo = 'bar';`} lang="js" />
<!-- Optional: Customize your theme. -->
<Code code={String.raw`const foo = 'bar';`} lang="js" theme="dark-plus" />
<!-- Optional: Enable word wrapping. -->
<Code code={String.raw`const foo = 'bar';`} lang="js" wrap />
<!-- Optional: Output inline code. -->
<p>
  <Code code={String.raw`const foo = 'bar';`} lang="js" inline />
  will be rendered inline.
</p>
@ttmc
Copy link
Author

ttmc commented Feb 28, 2024

The same change could be made to the example code given in the Astro docs about the Prism component, i.e.

---
import { Prism } from '@astrojs/prism';
---
<Prism lang="js" code={String.raw`const foo = 'bar';`} />

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant