How to capture if current vendor is selected

2020-08-01 11:57发布

问题:

In my sidebar on the collection pages and index, I have listed all vendors with the code below. Now I want to add an .active class to the <li> when that particular vendor is selected. I want to do the same thing with a list of product types. How do I check which vendor is selected?

I tried {% if collection.handle == vendor %}. But it returns null as it can only capture collections names.

<ul class="nav">
  {% for vendor in shop.vendors %}
      <li class="collection-container {% if collection.handle == vendor %}active {% endif %}">{{ vendor | link_to_vendor }}</li>
  {% endfor %}
</ul>

Please note that the url is constructed as /collections/types?q=Nike and that after the = comes the vendor. I want to try to somehow capture on which current collection the user is navigating and add an active tag throughout the foreach loop.

I realise it can be done by creating collections for each vendor and product type and using collection.handel, but I am interested in trying to solve it by capturing the last bit of the URL.

回答1:

To display all vendors in shop

<ul class="filter">
  {% for Vendor in shop.vendors %}
    {% if shop.vendors contains Vendor %}
      <li class="{% if collection.current_vendor == Vendor %}active{% endif %}">
        {{ Vendor | link_to_vendor }}
      </li>
    {% endif %}
  {% endfor %}
</ul>

If you want to have a specific list of vendors

<ul class="filter">
  {% assign myvendor = 'samsung,xaomi,Nokia' | split:"," %}
  {% for Vendor in myvendor %}
    {% if shop.vendors contains Vendor %}
      <li class="{% if collection.current_vendor == Vendor %}active{% endif%}">
        {{ Vendor | link_to_vendor }}
      </li>
    {% endif %}
  {% endfor %}
</ul>