One of the things I did­n’t like about the pre­vi­ous ver­sion of this site’s de­sign was how promi­nent the ad was on smaller screens. Instead, I wanted to place the ad af­ter the first post on the home­page.

Thankfully, Jekyll (actually, Liquid) al­lows us to do this with the forloop ob­ject. There are lots of things you can do with this, so read the of­fi­cial doc­u­men­ta­tion if you want to learn more. We’ll first setup our post loop:

<ul class="posts">
{% for post in site.posts %}
<li>
<span class="post-title">{{ post.title }}</span>
<span class="post-description">{{ post.excerpt }}</span>
</li>
{% endfor %}
</ul>

Now, we’ll place our ad us­ing forloop.first. forloop.first will re­turn true if it’s the first it­er­a­tion of the loop.

<ul class="posts">
{% for post in site.posts %}
<li>
<span class="post-title">{{ post.title }}</span>
<span class="post-description">{{ post.excerpt }}</span>
</li>
{% if forloop.first %}
<!-- put your ad markup in here -->
{% endif %}
{% endfor %}
</ul>

In plain English: place the ad di­rectly af­ter the first item in the loop.

Boom! Now our ad in­te­grates bet­ter with the con­tent, and is a bet­ter ex­pe­ri­ence for read­ers be­cause they’re aren’t hit with an ad as the first thing they see.

Series Hacking Jekyll

As I learn things about Jekyll, I try to write about them.

View Series →