Is there a way of embedding the content of a file (from the projects repo) in Githubs markdown?
I have a code sample and want to embed it in the projects readme.
There are two ways to format code in Markdown. You can either use inline code, by putting backticks (`) around parts of a line, or you can use a code block, which some renderers will apply syntax highlighting to.
Markdown supports HTML, so if you need to, say, embed a YouTube video, you can just copy and paste the embed code from them, drop it into a Markdown document, and you should be good to go.
Embedding Code in Markdown. If you're writing your code in markdown, the easiest way to embed snippets is to use "fenced code blocks", which also allows syntax highlighting. For examples in practice, see this assemble boilerplate for markdown projects, in particular take a look at the code in these templates.
@Petros's answer is (still) correct, however I got annoyed enough with this that I've created a tool to automate the copying and keep your readme synchronised with the source - https://github.com/zakhenry/embedme
Example usage from the accepted answer
Insert a comment into the code fence
```rb # path/to/your/file.rb ```
Run npx embedme README.md
(this assumes you have Nodejs installed)
The README will be written in-place, with the content of the file following your comment
```rb # path/to/your/file.rb class MyClass end ```
Note that as the comment is still there, you can happily re-run npx embedme README.md
again and it won't make any change.
If you have CI, you can also run npx embedme --verify README.md
which will return 1
if it detects a diff (this would mean that the source was updated without the readme being updated).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With