12

I am trying to check if my current page is a collection page not a single product page in some collection.

I mean for example if someone goes to collection page of shoes then I can check using collection.handle == 'Shoes' but if I select a product from that page then it will still give me true But I want my condition to be true on if it is collection page. Thanks for your Help!

cm_w89
  • 157
  • 1
  • 2
  • 8

5 Answers5

19

Use this simple way with template:

{% if template contains 'collection' %}
    Do something
{% endif %}

As Shopify evolves you can now use this:

{% if template.name == 'collection' %}
    Do something
{% endif %}
Alice Girard
  • 2,077
  • 11
  • 21
  • Works also if you need to check if you are on a product page with if template contains 'product'. – Alice Girard Oct 08 '16 at 16:01
  • Be careful... any product with a name containing "collection" will register true for this. Granted that chance is rare, but it's out there. – Augie Gardner Dec 06 '17 at 01:38
  • 1
    Absolutely not. The variable checks template name. So if you are on a product page, the variable contains «product». Even if {{ product.name }} contains the word Collection, this is not related to template name. – Alice Girard Dec 07 '17 at 08:44
  • I think I understand. I had that mixed up with the location href. Cool, thanks – Augie Gardner Dec 07 '17 at 08:49
10

A safer alternative to avoid rare cases where templates are badly named would be to use request.page_type - see the Shopify docs

{% if request.page_type == 'collection' %}
  Do something
{% endif %}
codinghands
  • 1,741
  • 2
  • 18
  • 31
  • I don't think this is correct, template.name is not the user given name of the template but actually the template type: https://shopify.dev/api/liquid/objects/template#template-name Could be a change since you wrote the answer, I have no idea :) – Luke Nov 15 '22 at 13:26
6

I would use:

{% if template == 'collection' %}
  Do something
{% endif %}

Because if you use contains and not == (equal to) you may run risk of it changing down the line if you ever created a new template which contained the word collection?

Allsops
  • 123
  • 1
  • 17
1

You can try this in condition.

{%if request.page_type == "collection" %} 
--- True if visit collection page or sub collection page. ---
{% endif %}

Thanks.

0

For defining a site wide page type I like this :

<body _pagetype="{{ request.page_type | handle }}">
MatteoOreficeIT
  • 190
  • 2
  • 5