How to add a copy-to-clipboard button to code blocks

This is a simple example using Hugo’s default syntax highlighter (Chroma) in conjunction with clipboard.js.

git clone --single-branch -b hugo-forum-topic-49633 https://github.com/jmooring/hugo-testing hugo-forum-topic-49633
cd hugo-forum-topic-49633
npm ci
hugo server

This works with code blocks that have:

  • No line numbers
  • Line numbers inline
  • Line numbers in a table cell

Files of interest

  • assets/js/*
  • assets/sass/*
  • layouts/_default/baseof.html (lines 7-8)
  • layouts/partials/head/*

The copy button appears when you place the cursor anywhere within the code block.

2 Likes