How to add a title to code block on Hugo blog
This article explains how to add a title to code block on Hugo blog.
This article explains how to add a title to code block on Hugo blog.
The following lists are the table of contents about this article.
Target audience
- Those who want to add a title to code block on Hugo blog.
Environment
- Hugo 0.57.2
- Hugo-extended 0.58.2
Preconditions
- Installed Hugo and Hugo-extended
Add a title to code block
Add JavaScript code
Add the following code to static/js/add-on.js.
I use IIFE (Immediately Invoked Function Expression) because I want to narrow the scope of a variable.
(function addTitleToCodeBlock() {
let list = document.body.getElementsByClassName("highlight");
for (i = 0; i <= list.length - 1; i++) {
let code = list[i].firstElementChild.firstElementChild;
let codeName = code ? code.className.split(":")[1] : null;
if (codeName) {
let div = document.createElement("div");
div.textContent = codeName;
div.classList.add("code-name");
code.parentNode.insertBefore(div, code);
}
}
}());
Add CSS code
Add the following code to static/css/add-on.css.
pre.chroma code {
margin-top: -28px;
padding-top: 40px;
padding-bottom: 12px;
}
.code-name {
display: inline-block;
position: relative;
padding: 4px 8px;
background-color: #E7E9EB;
color: #485A60;
font-size: 13px;
font-weight: 400;
}
How to set a title
When you use code block, add “:[title]” to after language name.
The following thing is example.
```javascript:test.js
console.log("Have a nice blog life!!!");
```
That's it! It's so easy! Thank you very much author of above codes! Guys, have a nice blog life!