Search code examples
jekyllgithub-pages

Embed file in Jekyll blog post


Is there a way to embed a file in a Jekyll blog post markdown?

I understand that one can add a permalink to a repo's README file in the format https://github.com/myaccount/myrepo/blob/some-hash/myfile.py#L1-L4 and a preview would show up in the rendered markdown.

Is there a way to do the same with a Jekyll markdown post?


Solution

  • You can include a complete sample like this:

    <pre>
        <code>
            {% include samples/trafikito.html %}
        </code>
    </pre>
    

    For a preview of a certain part of a file, there seem to be some options that I have not used/tested yet.

    From https://hblok.net/blog/posts/2016/10/23/jekyll-include-partial-snippets-of-code/

    Liquid slice and split

    Using the Liquid capture block, it's possible to read a file and store it as a string variable. It can then be processed by Liquid instead of the plugin, and works fine with Github pages. The Liquid syntax is certainly verbose, but it gets the job done.

    An initial implementation cutting the file content as a single string looked like this. However, it is far from ideal, since the character index and count will shift with any source code modifications on the included file.

    {% capture filecontent %}
        {% include src/HelloWorld.java %}
    {% endcapture %}
    
    {% highlight java %}
        {{ filecontent | slice: 132, 57 }}
    {% endhighlight %}
      
    

    A slightly better solution uses the same idea, but operates on line numbers instead. It is almost as fragile when it comes to changes, but at least usable.

    {% capture filecontent %}
        {% include src/HelloWorld.java %}
    {% endcapture %}
    
    {% assign lines = filecontent | newline_to_br | split: '<br />' %}
    {% highlight java %}
        {% for line in lines offset:10 limit:5 %}{{ line }}{% endfor %}
    {% endhighlight %}
    

    Let me know if this works and if so which worked best for you. Thanks.