Blog

Choose a Category
  • Create a variable for the active tag on a collection page in Shopify

    Shopify gives you an easy way to highlight the active tag on a collection page. This is helpful to add a indicator on a link. But, what if you want to use an active tag to control the layout of a collection page with a tag filter applied. Here is code that will produce the variable "active_tag" that you can use in your templates.

    {% for tag in collection.tags %}
      {% capture tag_code %}
        {{ tag | highlight_active_tag | link_to_tag: tag }} ::{{ tag }}::
      {% endcapture %}
      {% if tag_code contains 'active' %}
        {% assign active_tag_name = tag_code | split: '::' %}
        {% assign active_tag = active_tag_name[1] %}
      {% endif %}
    {% endfor %}

    One of the the ways I use this variable is to compare it to a tag listed in the theme settings to render a different layout snippnet for that tags collection page. This code would be used on the collections.liquid template. It checks to see if the active_tag is listed in a theme setting, and then renders a snippet for a product listing that it is in grid form. If that active_tag is not in that theme setting then use the default snippet for the product listings. 

    {% if settings.tags_to_display_as_grid contains active_tag %}
      {% include 'product-grid-item' with collection.handle %}
    {% else %}
      {% include 'product-row-item' with collection.handle %}
    {% endif %}

    An even easier way to use this bit of code would be to specify the tags you want directly in the collection.liquid template like so:

    {% if active_tag == 'Shoes' or active_tag == 'Dresses' %}
      {% include 'product-grid-item' with collection.handle %}
    {% else %}
      {% include 'product-row-item' with collection.handle %}
    {% endif %}

    Setting the "active_tag" variable to the collection's title if there is no active tag

    Let's say I want to be able to set the kind of layout used for the collection when there is no tag filter I would use this code to have the "active_tag" either be the name of the tag OR if there isn't any have it be the name of the current collection.

    {% for tag in collection.tags %}
      {% capture tag_code %}
        {{ tag | highlight_active_tag | link_to_tag: tag }} ::{{ tag }}::
      {% endcapture %}
      {% if tag_code contains 'active' %}
        {% assign active_tag_name = tag_code | split: '::' %}
        {% assign active_tag = active_tag_name[1] %}
      {% endif %}
    {% endfor %}
    {% unless active_tag %}
      {% capture collection_downcase %}{{ collection.title | downcase }}{% endcapture %}
      {% assign active_tag = collection_downcase %}
    {% endunless %}