How to Use Gists to Show Code Snippets
You don’t need to make a new Gist for each code snippet. Instead, display a single file from a multi-file Gist
A GitHub Gist is arguably the best way to display code snippets in a Medium post. Syntax highlight alone makes it the ideal choice. A Gist will typically consist of multiple files, which inevitably leads to the question: how do I display an individual file? Unless you're a web developer, the answer is not obvious. This post will answer that question.
You can select a file from a Gist with multiple files by appending the URL with: ?file=fileName
Basics: how to insert a Gist
To insert a Gist into your post, simply copy the URL into the Medium editor and hit enter. Voila, you have some nicely formatted code displayed.
The code above was displayed using the following URL:
https://gist.github.com/lgloege/1dd2a8bd264ab13ad184cdfb73e6953e
However, this usually is not what you want. Typically you want to only display one file at a time.
Selecting a single file
To select a single file from a Gist all you have to do is append the URL with this:
?file=<name>
where <name>
is the name of a file in your Gist. Using the Gist above, <name>
could be :print_my_name.py
or print_my_city.py
.
For example, this would be the URL to display print_my_name.py
:
https://gist.github.com/lgloege/1dd2a8bd264ab13ad184cdfb73e6953e?file=print_my_name.py
While appending ?file=print_my_city.py to the URL displays the print_my_city.py
file:
Final thoughts and video demonstration
I hope this short post helps technical writers use Gists more effectively. Don’t make my mistake and think you have to make a new Gist each time you want to display a different code block. Instead, simply append the URL with ?file=<name>.
Thank you for reading and supporting Medium writers