While writing technical content for this blog, I usually find it tough to include source code in the posts in a way that makes it readable and appealing. I want it to be enjoyable to read the code, rather than a struggle.
This led me to explore various solutions and in this post I go over the options I considered and what I eventually found to work best for me.
In my search, I considered the following 3 options:
This is where I post the source code on gist.github.com and then embed the gist in the blog post.
- Gist embedding is natively supported in WordPress
- Amazing out of the box syntax highlighting
- Simple for the reader to copy the code directly from the post if they need to
- Content not rendered on some platforms e.g. In the Pocket mobile app and in the AMP version of the site
This is how a Gist embed looks:
WordPress Source Code Embed
This works through using some special tags directly in the post, and any text you put between these tags, is then interpreted as code and gets syntax-highlighted. More details on this on this WordPress Support page.
- Extremely simple to insert code right in the editor as the post author
- Simple for the reader to copy the code directly from the post
- Natively supported in WordPress
- Not the best syntax highlighting option
- Limited languages supported
I wasn’t able to properly embed the JSX code snippet above using this option without trying to pull my hair out, so to see how this option looks, I suggest you check it out in my previous post: A Practical Use Case for React’s componentDidUpdate
This is a relatively new option and one that I’m excited to try out.
There’s an awesome website carbon.now.sh that claims to help you
create and share beautiful images of your source code, and it definitely fulfills this bold claim. All you have to do is post your code on the website and it generates a beautiful image of the source code that you can embed anywhere, including on a blog post.
- Truly beautiful images 😍
- Awesome syntax highlighting, almost exactly what you would get in your editor
- A variety of themes to choose from
- Directly import source code from GitHub gist (carbon.now.sh/GIST_ID_HERE)
- Generates images, so it’s not possible to copy the source code from the post
This is how this ends up looking on a post:
My workflow now involves posting the code in GitHub Gist and using the Gist ID to generate an image on Carbon. In the actual post, I then embed the Carbon generated image and add a link to the gist. This way I can take advantage of both these awesome services.
To see all of these options in a practical post, you can check out my previous post: A Practical Use Case for React’s componentDidUpdate