Reputation: 33
I have an issue where I need to display tags in a specific order, based on the first part of the tag. For example, I have a list of potential product tags:
category_electronics
size_large
color_black
color_brown
weight_10
And I need them to sort based on a pre-set order applied to the first part of the tags (before the underscores), for example:
size
color
weight
category
So with the above example, I'd want to end up with the list sorted like:
size_large
color_black
color_brown
weight_10
category_electronics
If the full tag names were all known, this would be simple, as I could just do something like:
{% assign tags = 'size_large,color_black,color_brown,weight_10,category_electronics' | split: ',' %}
{% for t in tags %}
{% assign tag = t | strip %}
{% if product.tags contains tag %}
<li>{{ tag }}</li>
{% endif %}
{% endfor %}
{% endif %}
However, that is not the case. The value after the underscore in the tag is variable, and there could be multiple occurrences of any of the tag groups (ie. size above) for any single product.
It seems I'd need to use some kind of associative array to make this happen, but I can't quite wrap my head around how that would be done.
Upvotes: 0
Views: 1906
Reputation: 2559
The following should work:
{%- assign tag_groups = "size,color,weight,category" | split: "," -%}
{%- assign sorted_tags = "" -%}
{%- for group in tag_groups -%}
{% for tag in product.tags %}
{%- assign tag_group = tag | split: "_" | first -%}
{%- if tag_group == group -%}
{%- assign sorted_tags = sorted_tags | append: tag | append: "," -%}
{%- endif -%}
{% endfor %}
{%- endfor -%}
{%- assign sorted_tags_arr = sorted_tags | remove_last: "," | split: "," -%}
{%- for tag in sorted_tags_arr -%}
{{- tag -}}<br>
{%- endfor -%}
Upvotes: 1