Categories
Code

Using forloop in Jekyll for Placing Ads

One of the things I didn’t like about the previous version of this site’s design was how prominent the ad was on smaller screens. Instead, I wanted to place the ad after the first post on the homepage.

Thankfully, Jekyll (actually, Liquid) allows us to do this with the forloop object. There are lots of things you can do with this, so read the official documentation 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 using forloop.first. forloop.first will return true if it’s the first iteration 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 directly after the first item in the loop.

Boom! Now our ad integrates better with the content, and is a better experience for readers because they’re aren’t hit with an ad as the first thing they see.

By Timmmmy

A human hoping to be empathetic and kind with all. I'm a geek, coffee drinker, stoner, maker of things, and forever an optimist. Brightly-colored clothes weren't enough, so I dye my hair too (he/him)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s