Many of us use theclass for CSS and JavaScript hooks and just like in WordPress it’s pretty easy to add a number of useful classes to our
element in Shopify.
Here are a few ideas that you might find useful placing in your main (or alternate) layout file:
Add the currently rendered template name to the body class
In this example, we are using模板
to return the name of the currently used template. Some examples of this are:
This can be really useful when you need to target a specific alternate template for example.
Add the currently rendered product handle to the body class
Building on this we may wish to add the current producthandle
to our body class. To keep things neat and tidy we can use anif
statement to conditionally add the product handle only when we are viewing a product:
Note how I include the space before the{{ product.handle }}
output tag.
If you are using alternate product templates you may wish to use thecontains
operator instead:
Add the current page title to the body class
Some themes also add the current page title to the body element in the form of an id, building on the above our code would now look as follows:
Note in this example we are using the Liquid filterhandleize
to ensure that theid
orclass
that we add is URL safe and therefore easy to reference in our CSS and JS files. For example, it will turn a page title of “Blue Jeans” into “blue-jeans”.
Add the currently viewed collection’s name to the body class
For good measure, we could even add in a check for collections and add that too:
It’s pretty easy to adjust this logic for your own purposes. Again you may wish to use thecontains
operator if you are utilising alternate templates.
Summary
Hopefully you’ve seen how flexible Liquid is in the above examples. Being able to add a variety of classes to theelement gives us useful hooks that we can use in CSS and JavaScript.
Learning Liquid: Getting Started with Shopify Theming
Get this free guide and learn practical tips, tricks, and techniques to start modifying, developing, and building Shopify themes.
By entering your email - we’ll also send you marketing emails related to Shopify. You can unsubscribe anytime. Note: the guide won't be delivered to role-based emails, like info@, developer@, etc.