a-luna / aaronluna.dev

My personal website/blog/portfolio, built with Hugo
https://aaronluna.dev
3 stars 1 forks source link

blog/add-copy-button-to-code-blocks-hugo-chroma/ #49

Open utterances-bot opened 4 years ago

utterances-bot commented 4 years ago

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/

lunawen commented 4 years ago

Thanks for sharing! I just added this button in my hugo site :)

a-luna commented 4 years ago

I’m glad you found it helpful, thanks for letting me know!

rahulrai-in commented 3 years ago

Thanks for the article. Can you share how you added the name of the language on top of the code blocks?

a-luna commented 3 years ago

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!

rahulrai-in commented 3 years ago

Thanks so much!

hnakamur commented 3 years ago

Thanks for sharing such a nice feature! I just added this button to my blog.

rahulrai-in commented 3 years ago

Me too. It's awesome 👏

HaoZeke commented 1 year ago

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.