Filenames for code blocks

I have a project where I want to be able to provide filenames for code blocks. So if I make a code block for, say, some Go code and want to specify that the code is in main.go, I’d like main.go to be on top of the block. Ideally, I’d like to be able to achieve that using something like this:

```go filename="main.go"
package main

func main() {
        println("Hugo rules!!!!")
}
```

Has anyone found a good way to make this happen? I’d be okay using JavaScript for this. I do have some ideas, just wanted to see if anyone had a solution more elegant than the ones I’m concocting :wink:

This will set the title attribute of the containing element.

```go {title="main.go"}
package main

func main() {
        println("Hugo rules!!!!")
}
```

Then find all the code blocks on the page with a title attribute and insert a <div> or whatever before each of them.

var els = document.getElementsByClassName("highlight");
for (var i = 0; i < els.length; i++) {
  if (els[i].title.length) {
    var newNode = document.createElement("div");
    var textNode = document.createTextNode(els[i].title);
    newNode.appendChild(textNode);
    newNode.classList.add("highlight-title");
    els[i].parentNode.insertBefore(newNode, els[i]);
  }
}

You will end up with:

<div class="highlight-title">something</div>

See: https://caniuse.com/?search=insertBefore

1 Like

You could also use a shortcode solution.

For example, you could wrap the built-in highlight shortcode to be labelled by a filename.

Shortcode Template

{{ $filename := .Get "filename" }}
{{ $lang := .Get "lang" }}
{{ $options := .Get "options" }}
{{ $input := (trim .Inner "\n\r") }}

<strong>Filename:</strong> <code>{{ $filename }}</code>

{{ highlight $input $lang $options }}

Sample Usage

{{< labelled-highlight lang="go" filename="main.go" >}}
package main

func main() {
        println("Hugo rules!!!!")
}
{{</ labelled-highlight >}}

Sample Output as Screenshot

Screen Shot 2021-04-21 at 11.03.51 PM

2 Likes

@zwbetz @jmooring These are both excellent solutions! I love that one of you provided a JavaScript-based one and the other provided a more “Hugo native” one. Such an awesome and helpful community :heart:

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.