356 words
2 minutes
Fuwari 给代码块添加标题栏
效果
src/example.md
md
```md file=src/example.md
example
```
NOTE向上面这样在语言后面加上
file=文件名
,即可在代码块上方显示文件名。
教程
- 在
plugins
文件夹下创建remark-code-title.js
文件
plugins/remark-code-title.js
js
import { visit } from 'unist-util-visit'
export function remarkCodeTitle() {
return (tree, { data }) => {
const nodesToInsert = []
visit(tree, 'code', (node, index, parent) => {
const language = node.lang
let meta = node.meta
if (!language) {
return
}
const className = 'remark-code-title'
let titleNode
// 只显示语言
titleNode = {
type: 'html',
value: `<div class="${className}">
<div id="only-lang">${language}</div>
<div id="separate-line"></div>
</div>`.trim(),
}
if (meta) {
// 排除掉其他 meta 项
const metas = meta.split(' ').filter(m => m.includes('file='))
if (metas.length > 0) {
meta = metas[0].replace('file=', '')
// 显示文件名和语言
titleNode = {
type: 'html',
value: `<div class="${className}">
<div id="filename-with-lang">
<div>${meta}</div>
<div>${language}</div>
</div>
<div id="separate-line">
</div>
</div>`.trim(),
}
// 保存需要插入的元素
nodesToInsert.push({ parent, index, titleNode })
}
}
})
// 插入元素
for (const { parent, index, titleNode } of nodesToInsert.reverse()) {
parent.children.splice(index, 0, titleNode)
}
}
}
- 在
Markdown.astro
的末尾添加css
样式
components/misc/Markdown.astro
astro
<style is:global>
.remark-code-title #filename-with-lang {
padding: 8px 25px;
display: flex;
direction: row;
justify-content: space-between
}
.remark-code-title #separate-line {
padding: 8px 0 3px;
border-top: 1px solid #e2e2e3
}
html.dark .remark-code-title #separate-line {
border-top: 1px solid rgb(63,62,62)
}
.remark-code-title #only-lang {
padding: 8px 25px;
display: flex;
direction: row;
justify-content: end
}
@media screen and (max-width: 1024px) {
.remark-code-title {
font-size:small
}
.remark-code-title #row2 {
padding: 8px 0 6px
}
}
</style>
- 在
astro.config.mjs
中导入插件
astro.config.mjs
js
import { remarkCodeTitle } from "./src/plugins/remark-code-title.js";
export default defineConfig({
markdown: {
remarkPlugins: [
// ...
remarkCodeTitle,
],
},
});
Fuwari 给代码块添加标题栏
https://astronaut.github.io/posts/how-to-add-code-block-title/