skip to Main Content

I’m trying to retrieve the most recent article on a blog. My current code below does not output anything.

{% for article in blogs['myblog'].articles.last %}
  {{ article.title }}
{% endfor %}

2

Answers


  1. It can be done like this using forloop.last:

    {% for article in blogs['myblog'].articles %}
        {% if forloop.last == true %}
             {{ article.title }}
        {% endif %}
    {% endfor %}
    

    This assumes that blogs is a variable. Otherwise, try replacing blogs['myblog'].articles with blog.articles.

    Login or Signup to reply.
  2. You don’t need a loop in order to access the last item.

    {% assign article = blogs['myblog'].articles.last %}
    

    This will set article to the last item. You can then use it as expected.

    {{ article.title }}
    

    Docs: https://shopify.dev/docs/themes/liquid/reference/filters/array-filters#last

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search