Skip to content

How to use with Astro

We export our own Astro component that is compatible with the <Code> component found at astro:components.

You can use the example below to see how it works.

---
import { Code } from 'astro:components';
import CodeCage from 'code-cage/astro';
// Multiline code is best done this way
const css = `.test {
color: limegreen;
}`
const js = `(function() {
console.log('test successful!');
})();`
---
<CodeCage>
<Code slot="html" lang="html" code="<div class='test'>Testing</div>" />
<Code slot="css" lang="css" code={css} />
<Code slot="js" lang="js" code={js} />
</CodeCage>

For this example, we’re going to use the Starlight theme’s <Code> component. Feel free to use whatever syntax highlighter you are currently using, as long as it outputs HTML it should work.

---
import { Code } from '@astrojs/starlight/components';
interface Props {
html: string;
css: string;
js: string;
}
---
<code-cage use-slots>
<span slot="html"><Code code={Astro.props.html} lang="html" /></span>
<span slot="css"><Code code={Astro.props.css} lang="css" /></span>
<span slot="js"><Code code={Astro.props.js} lang="js" /></span>
</code-cage>
<script>
import { define } from 'code-cage';
define();
</script>

Then use it as you would any other .astro component.

---
import CodeCage from './components/CodeCage.astro';
const serverRenderedHTMLString = `<div>...</div>`;
---
<CodeCage
html={serverRenderedHTMLString}
css=".test {
color: limegreen;
}"
js="(function() {
console.log('testing');
})();"
/>