Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community!

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial


Add odd/even classnames to a Jekyll post loop

Hey, I wanted to know how you would add odd/even class names to a Jekyll post loop.

Here is my code:

<ul class="entries">
    {% for post in site.posts %}
    <li><a class="entry" href="{{ post.url }}">
        <img src="{{ post.image }}">
        <h2>{{ post.title }}</h2>
    {% endfor %}

This is the generated code to be

<ul class="entries">
    <li><a class="entry odd" href="posts/post1">
        <img src="img1.jpg">
        <h2>Post 1</h2>
    <li><a class="entry" href="posts/post2">
        <img src="img2.jpg">
        <h2>Post 2</h2>
    <li><a class="entry odd" href="posts/post3">
        <img src="img3.jpg">
        <h2>Post 3</h2>
    <li><a class="entry" href="posts/post4">
        <img src="img4.jpg">
        <h2>Post 4</h2>

I really need it for my first project. Thanks in advance!

4 Answers

Hi Enrique,

What you need is something that alternates between states.

You could use a Boolean, which has only two states, or something which behaves like it.

In this case, with pseudo-logic, you could start off with a variable like:

odd = true;
for posts in site.posts
    ... code ...
    if odd == true
        ... output odd ...

    odd = !odd // flips the Boolean from true to false

Is that Jekyll code? As in Jekyll the static site generator?


Hi Enrique,

No, it isn't. It's just a pseudo-code to suggest a way to tackle the problem.

The actual code isn't syntactically accurate, but merely to illustrate a path to solving it.

If you know the jekyll syntax, you could look for parallels to execute a similar logic?

I've done that logic before with PHP but can't seem to find a way to do it with Jekyll. :sob: