GitHub provides a nice way of selecting and embedding some code inside of an issue, to single out the exact part that you want to talk about within the comment.
I quite like this feature, and I wished that Hugo would have something similar. For the most part, website additions are done via shortcodes. This is where Hugo will automatically copy-paste some templates right into your page, but to embed code from another website needs a different approach.
To create this embed, I decided to have a peek at how GitHub (and other sites) implemented this feature, and it’s surprisingly simple. Just using HTML tables and some CSS, I can create an embed that looks pretty and is very functional.
Since this is done externally to the Hugo build process, it needs some preprocessing or an automated script to convert the source file into the widget itself - nobody wants to painstakingly convert it all manually. As such, I made a little Python preprocessor that is available on GitHub at krisjdev/code-embedder. The repository also contains the HTML/CSS for the embed, but it’s been tuned specifically for the PaperMod theme - if you want to use it, you’ll have to make some adjustments. Check it out :)
krisjdev/code-embedder/preprocess.py
Lines 32 to 38 from 541c8794
32 | def fetch_content(self): |
33 | open_url = urllib.request.urlopen(self.download_path) |
34 | encoding = open_url.headers.get_content_charset() |
35 | content = open_url.readlines() |
36 | |
37 | self.file_content = content |
38 | self.file_encoding = encoding |
It does need some tweaks, namely proper syntax highlighting depending on what language is selected but I’m very happy with it as is.