ses
ses

Reputation: 13342

Passing previously assigned variable in `{% for` block in Shopify

In blog-templte.liquid

{% assign articleSortOrder = '' %} 
 ....

{% for article in blog.articles {{articleSortOrder}} %}  

got an error : Liquid syntax error: Unexpected character { in "article in blog.articles {{articleSortOrder}}"

The intention is to pass the variable to sort the articles depending on some condition.

Q: is how to make it work?

Upvotes: 0

Views: 1097

Answers (1)

drip
drip

Reputation: 12943

This is not a valid liquid code:

{% for article in blog.articles {{articleSortOrder}} %}

You can't pass a liquid inside a liquid, a.k.a {% {{ }} %}


In addition for loops accept only a few parameters:

  • reversed - which will reverse the loop
  • limit - which will limit the iterations
  • offset - which will make the loop skip a specific set number of items

Sort is not one of them.

You can read more about the for loop here: https://shopify.dev/docs/liquid/reference/tags/iteration-tags


In order to sort the blog in a specific way you must code it like so:

{% assign articleSortOrder = '' %} 
{% assign blog_articles_sort = blog.articles | sort: articleSortOrder %}
{% for article in blog_articles_sort %}

{% endfor %}

Where you assign the articles in a specific variable and sort them.

Please have in mind that this will sort ONLY 50 articles.


If you like to sort more than 50 you will need to overwrite the paginate object {% paginate blog.articles by 9999 %}

Then your code will look like this:

{% paginate blog.articles by 9999 %}
  {% assign articleSortOrder = '' %} 
  {% assign blog_articles_sort = blog.articles | sort: articleSortOrder %}
  {% for article in blog_articles_sort %}

  {% endfor %}
{% endpaginate %}

More about paginate can be seen here: https://shopify.dev/docs/liquid/reference/tags/theme-tags/#paginate


Please have in mind that the sort function in Shopify is limited. You may need to sort them with javascript or another approach depending one what you are looking for.

Upvotes: 0

Related Questions