Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to embed code from repo in github markdown?

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.

like image 982
Simon Avatar asked Apr 23 '12 12:04

Simon


People also ask

How do I embed code in Markdown?

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.

Can you embed in Markdown?

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.

Can you embed code snippets in Markdown?

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.


1 Answers

@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).

like image 130
Zak Henry Avatar answered Sep 29 '22 16:09

Zak Henry