Search code examples
shopifyliquid

Shopify - Logic to display handle of pages, collections, products and index on <body id="handle">?


Problem

I've found partial answers to this (like here and here) but get mixed results because it seems like grabbing the page handle is different depending on if the current page is a collection, a product, a page, a blog or index - is that correct?

Sorry if this is easy, I'm just a designer so am probably using incorrect search terms.

Attempt

I've been adding logic to the body tag with mixed results like this...

<body 
  {% if template.name != "index" %}id="{{ page.handle }}"{% endif %} 
  class="{{ template }}{% if template == "product" %} {{ product.handle }}{% endif %}
  {% if template == "collection" %} {{ collection.handle }}{% endif %}"
>

Question

If possible, I'd prefer to define a variable like "bodyID" or "bodyClass" and use logic to grab the handle no matter the page-type - is this possible?

Something like...

{%
   bodyID = ...logic to grab handle no matter the page-type...
%}

<body id="{{ bodyID }}"

Or is there another way people do this? Any help much appreciated. Cheers


Solution

  • OK, after more searching I found this and with a bit of logic to handle the index use case, this works and adds a useful ID hook onto the body tag...

    <body {% if template.name == "index" %}id="index"{% else %}id="{{ handle }}"{% endif %}>
    

    If anyone has a better way, let me know.