Preview
Example code with title and language properties
const code = `function greet() {
console.log("Hello, World!");
}`;
const highlighter = await highlight();
const html = highlighter.codeToHtml(code, {
lang: "javascript",
theme: "one-light",
});Output HTML with data-title and data-language attributes
<pre
class="shiki shiki-themes one-light one-dark-pro"
tabindex="0"
data-language="ts"
data-title="Example code with title and language properties"
>
<code>...</code>
</pre>Installation
shadcn/ui
shadcn/ui Command
pnpm dlx shadcn@latest add https://code-blocks.pheralb.dev/r/shiki-add-to-pre-element.jsonManual
- Create a
src/utils/shiki/transformers/add-to-pre-element.tsfile and add the following code:
.ts
import type { ShikiTransformer } from "shiki";
const addTitleProperty = (): ShikiTransformer => {
return {
name: "AddTitleProperty",
pre(node) {
const rawMeta = this.options.meta?.__raw;
if (!rawMeta) return;
const title = rawMeta.match(/title=(["'])(.*?)\1/)?.[2];
node.properties["data-title"] = title;
},
};
};
const addLanguageProperty = (): ShikiTransformer => {
return {
name: "AddLanguageProperty",
pre(node) {
node.properties["data-language"] = this.options.lang || "plaintext";
},
};
};
export { addTitleProperty, addLanguageProperty };- Update your
rehypeShikiplugin to use the new transformers:
.ts
import {
addTitleProperty,
addLanguageProperty,
} from "@/utils/shiki/transformers/add-to-pre-element";
const rehypeShikiOptions: RehypeShikiCoreOptions = {
//...
transformers: [addTitleProperty(), addLanguageProperty()],
};
export { rehypeShikiOptions };Usage
addTitleProperty
A transformer that adds a data-title attribute to the <pre> element if the code block has a title:
.mdx
```javascript title="My Code Block"
console.log("Hello, World!");
```Output:
.html
<pre data-title="My Code Block">
<code>...</code>
</pre>addLanguageProperty
A transformer that adds a data-language attribute to the <pre> element with the language of the code block:
.mdx
```python
print("Hello, World!")
```Output:
.html
<pre data-language="python">
<code>...</code>
</pre>