Search code examples
javascripthtmlhugogist

Display text value from Github Gist in Hugo site


I know I might be asking something quite simple but for the life of me I can't seem to get my head around this and I'm definitely overseeing something simple but I don't know what. Any help would be very appreciated.

I'm generating a static site using Hugo. On one of my pages, I want to create something like a progress bar, using a variable which I need to get from a file from a Github Gist.

Say this is the gist: https://gist.github.com/bogdanbacila/c5a9683089c74d613ad17cdedc08f56b#file-thesis-words-txt

The file only has one number, that's it. What I'm asking is how to get that number from the gist and store it in hugo or at least just display it in some raw html. I want to mention that I'm not looking to use the provided embedded text, I'd rather just get the raw value. At the end of the day all I need is to read and display the number from the raw link here: https://gist.githubusercontent.com/bogdanbacila/c5a9683089c74d613ad17cdedc08f56b/raw/8380782afede80d234209293d4c5033a890e44b6/thesis-words.txt

I've asked this question on the Hugo forum and that wasn't very helpful, instead of providing me with some guidance I got sent here. Here was my original question: https://discourse.gohugo.io/t/get-raw-content-from-github-gist-to-a-variable/38781

Any help would be greatly appreciated, I know there's something very obvious which I'm not seeing, please guide me to the right direction, this doesn't feel like it should be that complicated.

Best, Bogdan


Solution

  • You could fetch this data and store it in Hugo as a data file but I don't recommend it.

    Since Hugo is a static site generator, you would need to not only modify the data files in your repo every time the value changes, but re-build your site as well. Then you have to worry about running the script on a schedule. Meaning you can't be sure that the value is current the second someone visits your site. This is more headache than it's worth in my opinion.

    The better route would be to write some client-side JavaScript that makes a call to the raw URL of the gist to get the content. This is Hugo-agnostic which is why I suspect you were pointed here.

    From the Gists API docs:

    If you need the full contents of the file, you can make a GET request to the URL specified by raw_url.

    You can use something like the Fetch API for this or any other JS client. Simply make a GET request to the URL, parse the value from the response body, and write some JavaScript to insert the value in the DOM when someone makes a request to the page it's on.