Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jekyll place variable inside logic expression

Tags:

jekyll

liquid

I'm trying to do the following:

{% for post in site.categories.{{ post.designer }} %}

So that when placing the above code inside a single post, it can display a list of posts from the current post's category.

However I don't think it's working because it just keeps returning undefined. My question is, is it possible in Jekyll or Liquid to place variables inside logic expressions?

Thanks

like image 635
user2028856 Avatar asked Dec 31 '25 06:12

user2028856


1 Answers

I suppose that "designer" is the category of your post?
If yes, you can't get it via post.designer.

You need to use page.categories instead (according to Page variables).

A post can have more than one category, so you can't just place page.categories in your loop because it's an array.

There are two possible solutions:

  1. Loop through all the categories of the post, and then do your loop for each category:

    {% for cat in page.categories %}
      <h1>{{ cat }}</h1>
      <ul>
        {% for post in site.categories[cat] %}
          <li><a href="{{ post.url }}">{{ post.title }}</a></li>
        {% endfor %}
      </ul>
    {% endfor %}
    
  2. If your post has only one category, you can omit the outer loop from my first example and just use the first element of the page.categories array:

    <ul>
      {% for post in site.categories[page.categories.first] %}
        <li><a href="{{ post.url }}">{{ post.title }}</a></li>
      {% endfor %}
    </ul>
    

    or

    {% assign firstcat = page.categories | first %}
    
    <ul>
      {% for post in site.categories[firstcat] %}
        <li><a href="{{ post.url }}">{{ post.title }}</a></li>
      {% endfor %}
    </ul>
    
like image 144
Christian Specht Avatar answered Jan 06 '26 00:01

Christian Specht



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!