Inject Content into a Jekyll Post

Wednesday, January 14, 2015

Sverrir Sigmundarson has created a better method to do this. I suggest using his method which I have detailed here.

There was a period where 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 change something.

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.

I came up with the following solution.

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 the Google AdSense code.

There is probably a better way to do the above using Jekyll’s native Data Files functionality, but I have not tested it.

I ended up abandoning this solution because it was very tedious managing where the injected content was displayed and I ultimately didn’t 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.



comments powered by Disqus