There was a period of time when I wanted to inject an ad into a particular part of every Jekyll post. I did not want to put the actual ad markup in the middle of the Markdown text file because it was ugly and would be difficult to manage if I had to make changes.
I was already aware of a Jekyll native way to create a Read More or Continue Reading function without a plugin, so there had to be a way to adapt that. What follows are two solutions to inject content into a Jekyll post.
Solution 1
First, put the following line in every Markdown text file in the exact spot where you want the injected content to appear. If you don’t want a post to contain any injected content, simply don’t put the following line in the Markdown text file. The word ad can be changed to whatever you want.
<!-- ad -->
Second, put the following Liquid code into the Jekyll layout file that is responsible for generating your Jekyll posts. If you used a different word than ad above, be sure to change it in the appropriate spots in the Liquid code.
{% if content contains "<!-- ad -->" %}
{{ content | split:"<!-- ad -->" | first % }}
CONTENT TO INJECT
{{ content | split:"<!-- ad -->" | last % }}
{% else %}
{{ content }}
{% endif %}
Replace CONTENT TO INJECT with whatever content you want to inject. In my particular case, I was simply injecting Google AdSense code.
There is probably a better way to do the above using Jekyll’s Data Files functionality, but I have not tested it.
I ended up abandoning this solution because it was very tedious to manage where the injected content was displayed, and I ultimately did not like having ads in the middle of my posts.
Nevertheless, this is a concept that can hopefully be used for something more interesting than injecting ads.
Solution 2
Solution 1 worked, but it felt hacky and inelegant. Additionally, it could only inject content one time in a Jekyll post.
Sverrir Sigmundarson came up with a new method that is a lot more elegant than what I previously created. His method creates a new Jekyll Tag that can be injected many times anywhere in a Jekyll post.
Since publishing the Gist, Sverrir has written a blog post with an updated and more extensible Jekyll Tag. The updated method allows you to inject different content in different places within a Jekyll post.