简体   繁体   中英

Filter and group articles by tags in Shopify?

I'm trying to group blog articles in Shopify by tag in the main blog template. So far I have this, but when trying to compare the group_tag and article_tag it always returns false. The print out as the same thing on the front end, eg.

This articles tags: Hello World

FALSE Hello World != Hello World

{% for tag in blog.all_tags %}
    {% assign group_tag = tag %}

        <h2>{{ group_tag }}</h2>

        {% for article in blog.articles %}
            {% assign article_tag = article.tags %}

            <h3>{{ article.title }}</h3>
            <p>This articles tags: {{ article_tag }}</p>

              {% if 'group_tag' == 'article_tag' %}
                <p>TRUE {{ article_tag }} = {{ group_tag }}</p>
              {% else %}
                <p>FALSE {{ article_tag }} != {{ group_tag }}</p>
              {% endif %}

        {% endfor %}

{% endfor %}

Is there a better way to filter the articles or compare the values of tag (group_tag) and article.tags (article_tag)?

The reason they appear the same but the comparison returns false is group_tag is a string containing a single tag, whereas article_tag is an array of tags (that currently contains only one tag, "Hello World").

You also don't want quotation marks around the variable names. Eg {% if 'group_tag' == 'article_tag' %} should be {% if group_tag == article_tag %} .

I would suggest using the contains operator instead:

{% for group_tag in blog.all_tags %}
  <h2>{{ group_tag }}</h2>

  {% for article in blog.articles %}
    {% if article.tags contains group_tag %}
      <h3>{{ article.title }}</h3>
      <p>This article's tags: {{ article.tags }}</p>
    {% endif %}
  {% endfor %}

{% endfor %}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM