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

穿精又带淫゛_ 提交于 2020-03-26 04:02:26

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/60311092/passing-previously-assigned-variable-in-for-block-in-shopify

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!