Render hook to add "Copy code" buttons to codeblocks

A recent update to the Zen theme (@frjo) added a copy code button to code blocks via a code block render hook (render-codeblock.html). It works great! Thanks. However, I have a couple of code blocks that have line numbering enabled, but the line numbers are not being displayed.

Can anyone suggest how to upgrade the code block render hook with line number support? Thanks.

(I am currently rebuilding my site with the Zen theme at my staging site.)

looks likes there’s no special stuff inside that hook. so it renders using the default options from your config.

guess LineNos is at false (default) in yours.

to allow to add line numbers for a specific code block you may:

enable block level attributes: Markdown attributes

and pass the lineNos option to the code block:

```bash {class=foo linenos=inline}

more options here:transform.Highlight

as always. if you cannot get that running share your setup

The render-codeblock.html example in my Zen theme does not work well with line numbers.

If you look at the code that Hugo generates without this file you should be able to see what changes you need to make.

I should add this info to the themes docs.

I only have a couple of code blocks that have line numbers enabled. I have been debating with myself if I really need or want line numbers. For now, I am going to disable line numbers. I really like how the new render codeblock hook works.

For anyone else stumbling across this, you can also use JS to add copy buttons to code blocks without a code block render hook. We do this on Hugo’s documentation site.

This was originally discussed here:
https://discourse.gohugo.io/t/how-to-add-a-copy-to-clipboard-button-to-code-blocks/49633

Take it for a spin:

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
2 Likes