Open utterances-bot opened 4 years ago
Thanks for sharing! I just added this button in my hugo site :)
I’m glad you found it helpful, thanks for letting me know!
Thanks for the article. Can you share how you added the name of the language on top of the code blocks?
Sorry for the delay, the name of the language is automatically added to each code block because of a single CSS rule:
.chroma [data-lang]:before {
position: absolute;
z-index: 0;
top: -22px;
left: 0px;
content: attr(data-lang);
border-top-left-radius: 4px;
border-top-right-radius: 4px;
border-bottom-left-radius: 0;
border-bottom-right-radius: 0;
padding: 5px 10px 7px;
}
This will ONLY work with Chroma (the syntax highlighter included with Hugo), because the HTML produced by Chroma includes the name of the language as a data attribute:
<pre class="chroma">
<code class="language-python" data-lang="python">
...
Let me know if you have any other questions!
Thanks so much!
Thanks for sharing such a nice feature! I just added this button to my blog.
Me too. It's awesome 👏
This is really neat, I updated this to work with line numbers (without including them in the copied snippet) and to only load it on pages with pre
in my theme.
Hugo: Add Copy-to-Clipboard Button to Code Blocks with Vanilla JS-aaronluna.dev
Hugo includes a built-in syntax-highlighter called Chroma. Chroma is extremely fast since it is written in pure Go (like Hugo) and supports every language I can think of. Chroma’s speed is especially important since syntax highlighters are notorious for causing slow page loads. However, it lacks one vital feature — an easy way to copy a code block to the clipboard. I decided to document my implementation using only vanilla JS since every blog post I found for this issue relied on jquery to parse the DOM, which is completely unnecessary at this point.
https://aaronluna.dev/blog/add-copy-button-to-code-blocks-hugo-chroma/